/*
模块名称：收款
起始日期：2021-6-23
功能描述：
1、点击“刷新”，提取可收费患者列表。
2、双击列表中患者，提取患者对应收费项目明细，计算合计金额、应缴现金。
3、如需医保结算，点击“医保结算”进行医保卡预结算过程，计算医保结算之后需要支付的现金。
4、输出实付金额，计算找零。
5、点击“收费保存”进行数据存储、发票打印。
6、如发生打印机械故障，可点击“发票打印”，只进行打印，不再进行数据存储。
业务逻辑：
1.

*/
#include "form_sk.h"
#include "ui_form_sk.h"
#include "pub_var.h"
#include <QSettings>
#include <QDebug>
#include <QSqlError>
#include <QMessageBox>
#include <QDateTime>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QSqlRecord>

#include <QMetaType>

Form_sk::Form_sk(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_sk)
{
    ui->setupUi(this);

    this->setWindowTitle("收款－当前用户－"+pub::usr_name);     //窗口标题

    QSettings setIni("clin.ini", QSettings::IniFormat);     //配置文件

    QRect rct = setIni.value("windowState/sk").toRect();    //恢复当前窗口位置
    this->setGeometry(rct);

    //数据库连接
    qrm = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    qro2 = new QSqlQuery(pub::db_o);

    if( "1" == setIni.value("sk/autodisplay").toString()){  //自动刷新待收款列表
        ui->cbAutoFlash->setChecked(true);
    }else{
        ui->cbAutoFlash->setChecked(false);
    }

    QString printerName = setIni.value("sk/printer").toString();    //收款打印机名称

    //配置打印机
    prt= new QPrinter(QPrinter::HighResolution);
    prt->setPrinterName(printerName);

    qrm->exec("select p_width,p_height from com_printer_setting "
              "where p_type = '门诊收据' and p_item = '页面'");
    int w = 0, h = 0;
    if(qrm->next()){
        w = qrm->value(0).toInt();
        h = qrm->value(1).toInt();
    }else{
        QMessageBox::information(this,"错误","门诊收据打印参数缺失！");
    }

    QSizeF sz = QSizeF(w,h);
    QPageSize psz(sz,QPageSize::Millimeter,"mzsj",QPageSize::FuzzyMatch);
    prt->setPageSize(psz);

    QPageLayout pglot = QPageLayout(prt->pageLayout());
    QRectF szf = pglot.fullRect(QPageLayout::Point);

    int dotPerInch = prt->physicalDpiX();
    ptScale = double(dotPerInch) / 25.4 ;

    prt->setOrientation(QPrinter::Portrait);      // 纵向打印, Landscape 横向打印
    prt->setFullPage(true);
    pnt = new QPainter();

    QFont ft = this->font();

    ui->tvBzh->setFont(ft);   //待付款列表字体
    ui->tvXmmx->setFont(ft);   //待付款列表字体

    ft.setBold(true);

    //设置应收金额等字体颜色
    ui->leYjxj->setFont(ft);
    ui->leSf->setFont(ft);
    ui->leZl->setFont(ft);



    palCashNormal = ui->leYjxj->palette();
    palCashUnderline = ui->leYjxj->palette();
    palCashUnderline.setColor(QPalette::Text,"red");

//    pal.setColor(QPalette::Text,"blue");
//    ui->leSf->setPalette(palCashNormal);
//    ui->leZl->setPalette(pal);

    tm = new QTimer();
    connect(tm, SIGNAL(timeout()), this, SLOT(onTimerOut()));

    uiInit();//界面初始设定

    //初始化医保线程
    qDebug()<<"initialYb thread";
    ybBusiness = new ThreadYb(this);
    thread = new QThread();
    ybBusiness->moveToThread(thread);
    qDebug()<<"thread start";
    thread->start();

    //发出信号启动医保交易线程
    connect(this, SIGNAL(opThread(int, QString)),ybBusiness, SLOT(doWork(int, QString)),Qt::BlockingQueuedConnection);

    //连接线程返回信号
    connect(ybBusiness, SIGNAL(resultReady(int, QString, QString)),
            this, SLOT(handleRet(int, QString, QString)),Qt::BlockingQueuedConnection);

    //网络配置
    request.setUrl(QUrl(pub::hos_ybjy));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

}

Form_sk::~Form_sk()
{
    delete ui;
}

void Form_sk::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/sk", QVariant(this->geometry()));
    if(ui->cbAutoFlash->isChecked()){
        setIni.setValue("sk/autodisplay", 1);
    }else{
        setIni.setValue("sk/autodisplay", 0);
    }
}

void Form_sk::onTimerOut()
{
    //刷新提示信息
    if( ui->lbMode->text().isEmpty()){
        ui->lbMode->setText(statusMsg);
    }else{
        ui->lbMode->setText("");
    }
    qApp->processEvents();
}

void Form_sk::handleRet(const int r, const QString o1,const QString o2)
{

    qDebug()<<"recive signal from ybThread ...";
    businessRetVal = r;
    businessRetStr1 = o1;
    businessRetStr2 = o2;
    businessFinish = true;
}

void Form_sk::resizeEvent(QResizeEvent *event)
{

    Q_UNUSED(event);
    //窗口界面大小变化，重新设定

    ui->tvBzh->setColumnWidth(0, (ui->tvBzh->width() -50 ) * 0.33);
    ui->tvBzh->setColumnWidth(1, (ui->tvBzh->width() -50 ) * 0.33);
    ui->tvBzh->setColumnWidth(2, (ui->tvBzh->width() -50 ) * 0.33);

    ui->tvXmmx->setColumnWidth(0, (ui->tvXmmx->width() -50 ) * 0.35);
    ui->tvXmmx->setColumnWidth(1, (ui->tvXmmx->width() -50 ) * 0.25);
    ui->tvXmmx->setColumnWidth(2, (ui->tvXmmx->width() -50 ) * 0.1);
    ui->tvXmmx->setColumnWidth(3, (ui->tvXmmx->width() -50 ) * 0.1);
    ui->tvXmmx->setColumnWidth(4, (ui->tvXmmx->width() -50 ) * 0.2);

}

void Form_sk::on_pbTc_clicked()
{
    this->close();
}

void Form_sk::on_pbSx_clicked()
{
    //ui->pbPrint->setEnabled(false); //打印

    ui->leBzh->setText("");
    ui->leSf->setText("");
    ui->leYjxj->setPalette(palCashNormal);
    ui->leZl->setText("");
    ui->pbSfbc->setEnabled(false); //
    ui->pbYbjs->setEnabled(false); //
    ui->pbSx->setEnabled(false);
    ui->rbX->setChecked(true);      //现金
    ui->rbX->setEnabled(false);      //
    ui->rbK->setEnabled(false);      //
    ui->rbM->setEnabled(false);      //
    ui->rbZ->setEnabled(false);      //
    mdXmmx.setQuery(NULL);          //项目明细列表清空
    qApp->processEvents();  //刷新显示
    //刷新可收费患者列表

    sq = "select distinct f.card_no, r.name, r.dept_name, r.dept_code, "
         " f.clinic_code, to_char(r.reg_date, 'yyyy-mm-dd hh24:mi:ss')reg_dt,"
         "r.PAYKIND_CODE,r.PACT_CODE,r.PACT_NAME,r.MCARD_NO,r.MEDICAL_TYPE, "
         "to_char(r.birthday,'yyyy-mm-dd'),r.sex_code, r.idenno, r.card_type"
         " from fin_opb_feedetail f, fin_opr_register r "
         " where r.reg_date +1 > trunc(sysdate)  "
         " and f.clinic_code = r.clinic_code and f.pay_flag = '0'"
         " and r.valid_flag = '1' ";

    sq = sq + " order by reg_dt desc";

    mdBzh.setQuery(sq, pub::db_o);
    mdBzh.setHeaderData(0, Qt::Horizontal, "门诊号");
    mdBzh.setHeaderData(1, Qt::Horizontal, "姓名");
    mdBzh.setHeaderData(2, Qt::Horizontal, "诊室");
    ui->tvBzh->setModel(&mdBzh);
    ui->tvBzh->setColumnWidth(0, (ui->tvBzh->width() -50 ) * 0.33);
    ui->tvBzh->setColumnWidth(1, (ui->tvBzh->width() -50 ) * 0.33);
    ui->tvBzh->setColumnWidth(2, (ui->tvBzh->width() -50 ) * 0.33);
    ui->tvBzh->setColumnWidth(3, 0);
    ui->tvBzh->setColumnWidth(4, 0);
    ui->tvBzh->setColumnWidth(5, 0);
    ui->tvBzh->setColumnWidth(6, 0);
    ui->tvBzh->setColumnWidth(7, 0);
    ui->tvBzh->setColumnWidth(8, 0);
    ui->tvBzh->setColumnWidth(9, 0);
    ui->tvBzh->setColumnWidth(10, 0);
    ui->tvBzh->setColumnWidth(11, 0);
    ui->tvBzh->setColumnWidth(12, 0);
    ui->tvBzh->setColumnWidth(13, 0);
    ui->tvBzh->setColumnWidth(14, 0);
    ui->pbSx->setEnabled(true);
}

void Form_sk::on_tvBzh_doubleClicked(const QModelIndex &index)
{
    ui->pbPrint->setEnabled(false); //打印
    //提取被选中患者的相关信息
    patientInfo.clear();
    patientInfo["PATIENT_NAME"] = index.siblingAtColumn(1).data(0).toString();
    patientInfo["IDENNO"] = index.siblingAtColumn(13).data(0).toString();
    patientInfo["CARD_TYPE"] = index.siblingAtColumn(14).data(0).toString();
    patientInfo["CLINIC_CODE"] = index.siblingAtColumn(4).data(0).toString();
    patientInfo["CARD_NO"] = index.siblingAtColumn(0).data(0).toString();
    patientInfo["regDeptCode"] = index.siblingAtColumn(3).data(0).toString();
    patientInfo["REG_DATE"] = index.siblingAtColumn(5).data(0).toString();
    patientInfo["MCARD_NO"] = index.siblingAtColumn(9).data(0).toString();
    patientInfo["MEDICAL_TYPE"] = index.siblingAtColumn(10).data(0).toString();
    patientInfo["BIRTHDAY"] = index.siblingAtColumn(11).data(0).toString();
    patientInfo["SEX_CODE"] = index.siblingAtColumn(12).data(0).toString();

    ui->leBzh->setText(patientInfo["CARD_NO"] + "，" + patientInfo["PATIENT_NAME"] + "，"+
            index.siblingAtColumn(3).data(0).toString());

    //支付模式默认为现金，检测环境允许之后设置医保结算按钮有效，进行医保预结算成功之后，收费模式改为医保
    //ui->lbMode->setText("收费方式：现金 、POS机");
    ui->rbX->setChecked(true);
    if( "02" == index.siblingAtColumn(6).data(0).toString() && pub::useInsurance ){ //医保挂号，且医保环境有效
        ui->pbYbjs->setEnabled(true);
        //ui->rbX->setChecked(true);      //现金
        //ui->rbK->setEnabled(true);      //
        //ui->rbM->setEnabled(true);      //
        //ui->rbZ->setEnabled(true);      //
    }else{
        ui->pbYbjs->setEnabled(false);  //设置医保结算按钮无效
        //ui->rbX->setChecked(true);      //现金
        //ui->rbK->setEnabled(false);      //
        //ui->rbM->setEnabled(false);      //
        //ui->rbZ->setEnabled(false);      //
    }

    patientInfo["yb"] = "0";  //医保交易标志， 0未交易，1已交易

    patientInfo["PAYKIND_CODE"] = "01";//
    patientInfo["PACT_CODE"] = "1";//index.siblingAtColumn(7).data(0).toString();
    patientInfo["PACT_NAME"] = "现金";//index.siblingAtColumn(8).data(0).toString();
    patientInfo["currentInvoNo"] = "";//当前发票号预置为空，正式结算时填入实际发票号
    patientInfo["ybToken"] = "";//令牌
    patientInfo["ybMode"] = ""; //医保模式，card, code, id
    on_leBzh_returnPressed();

}

void Form_sk::on_leBzh_returnPressed()
{
    nonInsuItem = false;   //出现非医保项目
    hasInsuItem = false;//医保项目
    nonInsuAmount = 0;  //非医保金额
    //项目明细列表
    sq = "select item_name, specs,  qty / pack_qty lst_qty ,price_unit, own_cost,"
         " mo_order, item_code, unit_price / pack_qty unit_price, doct_code, doct_dept,"
         " qty rqty "
         " from fin_opb_feedetail "
         " where clinic_code = '"
            + patientInfo["CLINIC_CODE"]
            + "' and pay_flag <>'1' order by recipe_no, sequence_no ";

    //    sq = "select item_name, specs,  qty/pack_qty rqty ,price_unit, own_cost,"
    //         " mo_order, item_code, unit_price, doct_code, doct_dept "
    //         " from fin_opb_feedetail "
    //         " where clinic_code = '"
    //            + patientInfo["CLINIC_CODE"]
    //            + "' and pay_flag <>'1' order by recipe_no, sequence_no ";



    mdXmmx.setQuery(sq, pub::db_o);

    if(mdXmmx.rowCount() == 0){ //对应患者无收费明细，返回
        return;
    }

    mdXmmx.setHeaderData(0, Qt::Horizontal, "项目名称");
    mdXmmx.setHeaderData(1, Qt::Horizontal, "规格");
    mdXmmx.setHeaderData(2, Qt::Horizontal, "数量");
    mdXmmx.setHeaderData(3, Qt::Horizontal, "单位");
    mdXmmx.setHeaderData(4, Qt::Horizontal, "金额");

    ui->tvXmmx->setModel(&mdXmmx);
    ui->tvXmmx->setColumnWidth(0, (ui->tvXmmx->width() -50 ) * 0.35);
    ui->tvXmmx->setColumnWidth(1, (ui->tvXmmx->width() -50 ) * 0.25);
    ui->tvXmmx->setColumnWidth(2, (ui->tvXmmx->width() -50 ) * 0.1);
    ui->tvXmmx->setColumnWidth(3, (ui->tvXmmx->width() -50 ) * 0.1);
    ui->tvXmmx->setColumnWidth(4, (ui->tvXmmx->width() -50 ) * 0.2);
    ui->tvXmmx->setColumnWidth(5, 0);
    ui->tvXmmx->setColumnWidth(6, 0);
    ui->tvXmmx->setColumnWidth(7, 0);
    ui->tvXmmx->setColumnWidth(8, 0);
    ui->tvXmmx->setColumnWidth(9, 0);
    ui->tvXmmx->setColumnWidth(10, 0);

    //计算合计金额
    mdXmmx.query().first();
    double hjje = mdXmmx.query().value(4).toDouble();
    while(mdXmmx.query().next()){
        hjje = hjje + mdXmmx.query().value(4).toDouble();
    }
    ui->leHjje->setText(QString::asprintf("%.2f",hjje));
    ui->leYjxj->setText(ui->leHjje->text());
    ui->leZhzf->setText("0");
    ui->leSf->setText(ui->leYjxj->text());

    //设置收费结算按钮可用
    ui->pbSfbc->setEnabled(true);

    //提取数据到 lstItemDetail

    qro->prepare("select f.doct_dept,f.exec_dpcd,f.drug_quality,f.specs,f.price_unit,"
                 "f.pack_qty,f.qty,f.days,f.clinic_code,f.reg_dpcd,f.dose_once,"
                 "f.dose_unit,f.usage_code,f.use_name, f.dose_model_code,f.mo_order,"
                 "f.comb_no,f.recipe_no,f.sequence_no,f.frequency_code,"
                 "b.DRUG_TYPE,b.MIN_UNIT,b.RETAIL_PRICE,b.Drug_Code,B.TRADE_NAME, f.drug_flag ,"
                 " f.own_cost, f.doct_code, reg_dpcd,"
                 "(select empl_name from com_employee where rownum = 1 and empl_code = f.doct_code),"
                 "(select c.si_code from COM_DOCTOR_COMPARE c"
                 " where rownum = 1 and c.empl_code=f.doct_code and c.valied_state='1'),"
                 " to_char(f.oper_date,'yyyymmddhh24miss')"
                 " from fin_opb_feedetail f, pha_com_baseinfo b"
                 " where f.item_code = b.drug_code and f.pay_flag <>'1' and f.drug_flag = '1'"
                 " and f.clinic_code = :clinic_code"
                 " union "
                 "select f.doct_dept,f.exec_dpcd,f.drug_quality,f.specs,f.price_unit,"
                 "f.pack_qty,f.qty,f.days,f.clinic_code,f.reg_dpcd,f.dose_once,"
                 "f.dose_unit,f.usage_code,f.use_name, f.dose_model_code,f.mo_order,"
                 "f.comb_no,f.recipe_no,f.sequence_no,f.frequency_code,"
                 "'','',f.unit_price,f.item_code,f.item_name, '0'  , f.own_cost, f.doct_code, reg_dpcd,"
                 "(select empl_name from com_employee where rownum = 1 and empl_code = f.doct_code),"
                 "(select c.si_code from COM_DOCTOR_COMPARE c"
                 " where rownum = 1 and c.empl_code=f.doct_code and c.valied_state='1'),"
                 " to_char(f.oper_date,'yyyymmddhh24miss')"
                 " from fin_opb_feedetail f"
                 " where f.pay_flag <>'1' and f.drug_flag = '0'"
                 " and f.clinic_code = :clinic_code"
                 " order by recipe_no"
                 );
    qro->bindValue(":clinic_code", patientInfo["CLINIC_CODE"] );

    if(!qro->exec()){
        QMessageBox::information(this,"注意", " 提取数据失败！"+qro->lastError().text() );
        qDebug()<<qro->lastQuery();
        return;
    }

    QMap<QString, QString> mp;
    lstItemDetail.clear();
    while(qro->next()){

        mp["doct_dept"] = qro->value(0).toString();
        mp["DRUG_DEPT_CODE"] = qro->value(1).toString();
        mp["DRUG_QUALITY"] = qro->value(2).toString();
        mp["SPECS"] = qro->value(3).toString();
        mp["PACK_UNIT"] = qro->value(4).toString();
        mp["PACK_QTY"] = qro->value(5).toString();
        mp["APPLY_NUM"] = qro->value(6).toString();
        mp["DAYS"] = qro->value(7).toString();
        mp["PATIENT_ID"] = qro->value(8).toString();
        mp["PATIENT_DEPT"] = qro->value(9).toString();
        mp["DOSE_ONCE"] = qro->value(10).toString();
        mp["DOSE_UNIT"] = qro->value(11).toString();
        mp["USAGE_CODE"] = qro->value(12).toString();
        mp["USE_NAME"] = qro->value(13).toString();
        mp["DOSE_MODEL_CODE"] = qro->value(14).toString();
        mp["MO_ORDER"] = qro->value(15).toString();
        mp["COMB_NO"] = qro->value(16).toString();
        mp["RECIPE_NO"] = qro->value(17).toString();
        mp["SEQUENCE_NO"] = qro->value(18).toString();
        mp["DFQ_FREQ"] = qro->value(19).toString();
        mp["DRUG_TYPE"] = qro->value(20).toString();
        mp["MIN_UNIT"] = qro->value(21).toString();
        mp["RETAIL_PRICE"] = QString::asprintf("%.2f",qro->value(22).toDouble());
        mp["item_code"] = qro->value(23).toString();
        mp["TRADE_NAME"] = qro->value(24).toString();
        mp["drug_flag"] = qro->value(25).toString();
        mp["own_cost"] = qro->value(26).toString();
        mp["doct_code"] = qro->value(27).toString();
        mp["DEPT_CODE"] = qro->value(28).toString();
        mp["doct_name"] = qro->value(29).toString();
        mp["doct_si_code"] = qro->value(30).toString();
        mp["oper_date"] = qro->value(31).toString();

        //医保对照目录
        sq = "select med_list_codg,center_item_grade,center_rate,med_chrgitm_type from fin_com_compare "
             " where fixmedins_hilist_id = '" + mp["item_code"] + "'";

        if(!qro2->exec(sq)){
            QMessageBox::information(this,"注意", "读取 fin_com_compare 失败！"+qro2->lastError().text() );
            return;
        }

        if(qro2->next()){
            mp["center_code"] = qro2->value(0).toString();
            mp["center_item_grade"] = qro2->value(1).toString();
            mp["center_rate"] = qro2->value(2).toString();
            mp["has_compare"] = "1";
            mp["med_chrgitm_type"] = qro2->value(3).toString();
            hasInsuItem = true;
        }else{
            mp["center_code"] = "";
            mp["center_item_grade"] = "";
            mp["center_rate"] = "";
            mp["has_compare"] = "0";
            mp["med_chrgitm_type"] = "";
            nonInsuItem = true;    //出现非医保项目
            qDebug()<< "非医保项目，代码："<<mp["item_code"] ;
        }

        lstItemDetail << mp;
    }
    mp.clear();
    ui->pbSfbc->setEnabled(true); //

}

void Form_sk::on_leSf_returnPressed()
{
    //计算现金找零
    double yj, sf, zl;
    yj = ui->leYjxj->text().toDouble();
    sf = ui->leSf->text().toDouble();
    if(qFuzzyCompare(yj, sf)){
        zl = 0;
    }else if(sf > yj){
        zl = sf - yj ;
    }else{
        QMessageBox::information(this,"错误","实付款不能小于应付款！");
        return;
    }

    ui->leZl->setText(QString::asprintf("%.1f",zl));
}


void Form_sk::on_rbX_clicked()
{
    patientInfo["ybMode"] = "";
    patientInfo["yb"] = "0";
}

void Form_sk::on_rbK_clicked()
{
    patientInfo["ybMode"] = "card";
}

void Form_sk::on_rbM_clicked()
{
    patientInfo["ybMode"] = "code";
}

void Form_sk::on_rbZ_clicked()
{
    patientInfo["ybMode"] = "id" ;
}

void Form_sk::on_pbSfbc_clicked()
{
    if(ui->pbYbjs->isEnabled() && patientInfo["yb"] == "0"){
        QMessageBox:: StandardButton result= QMessageBox::warning(this, "注意", "医保挂号患者，确定本次结算不用医保，直接使用现金？",QMessageBox::Yes|QMessageBox::No);
        if(result == QMessageBox::No){
            return;
        }
    }

    ui->pbSfbc->setEnabled(false);  //开始收费流程，医保预结算和收费按钮禁用。
    ui->pbYbjs->setEnabled(false);  //
    ui->rbX->setChecked(true);      //现金

    qApp->processEvents();  //刷新显示
    if(patientInfo["yb"] == "1"){   //医保操作，首先进行身份验证

        //正式结算之前，清理数据

        //2205,撤销费用明细上传
        //预结算不分发票只算总数，医保结算时需要按每张发票计算，所以要清除数据重新上传。


        QJsonObject in,inpu,inpud;
        QJsonDocument indoc;
        putBaseIn(  in, "2205");

        inpu.insert("mdtrt_id", patientInfo["mdtrt_id"]);   //就诊ID
        inpu.insert("chrg_bchno", "0000");   //传“0000”，删除所有未结算数据
        inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());//

        inpud.insert("data",inpu);
        in.insert("input", inpud);
        indoc.setObject(in);
        //保存入参日志
        qDebug()<< currentInfno + " indoc"<<indoc;
        sq = "update com_business set v_in = '"
                + indoc.toJson(QJsonDocument::Compact)
                + "' where jyls = '" + currentMsgid + "'";

        if(!qrm->exec(sq)){
            QMessageBox::information(this,"错误","保存入参日志失败！");
            qDebug()<<sq;
        }

        QNetworkReply* reply = manager.post(request,indoc.toJson());
        QEventLoop eventLoop;
        QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
        eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。

        qDebug()<<" request " + currentInfno + " is returned ";

        QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

        if(!statusCode.isValid()){
            QMessageBox::warning(NULL,"注意", currentInfno + " http 请求状态错误: " + statusCode.toString());
            return ;
        }

        QNetworkReply::NetworkError err = reply->error();

        if(err != QNetworkReply::NoError){
            QMessageBox::warning(NULL,"注意",reply->errorString());
            return ;
        }

        QByteArray btret = reply->readAll();
        QString t = QString::fromLocal8Bit(btret);

        QJsonParseError json_error;

        QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
        if(json_error.error != 0 ){
            QMessageBox::warning(NULL,"注意", currentInfno + " 返回信息解析错误 " + json_error.errorString());

            return ;
        }
        qDebug()<< currentInfno + " outDoc "<<jsdc;
        QJsonObject jsob = jsdc.object();

        //保存出出参日志

        sq = "update com_business set v_out = '"
                + jsdc.toJson(QJsonDocument::Compact)
                + "' where jyls = '" + currentMsgid + "'";

        if(!qrm->exec(sq)){
            QMessageBox::information(this,"错误","保存出参日志失败！");
            qDebug()<<sq;
        }

        /*
        //中心无数据情况下执行 2205 会返回异常。
        if(jsob.value("infcode").toInt() != 0){
            QString t = jsob.value("err_msg").toString();
            QMessageBox::warning(NULL,"注意", currentInfno + " 交易失败：" + t );
            return ;
        }
*/

        //2205 结束

    }

    if(ui->leYjxj->text() == ui->leSf->text()){ //实付与应付相等，不需要四舍五入
        balanceFlag = false;    //不需要四舍五入
    }else{
        balanceFlag = true;    //平衡发票间四舍五入余额，非pos机支付现金时需要
        balance = 0;
        balanceSeq = 1;
    }

    //保存收费数据
    ui->lbMode->setText("保存收费数据");
    qApp->processEvents();  //刷新显示

    QMap<QString,QString> mp;   //list 公用变量
    int idx;    //索引下标
    bool stop = false;  //流程中止标志

    //计算库存是否充足
    qDebug()<<"计算库存是否充足";
    qro->prepare("select sum(f.qty), f.item_name, f.item_code, s.store_sum"
                 " from fin_opb_feedetail f, pha_com_stockinfo s"
                 " where f.drug_flag = '1' and f.item_code = s.drug_code "
                 " and f.exec_dpcd = s.drug_dept_code"
                 " and f.pay_flag <>'1' and f.clinic_code = :clinic_code"
                 " group by f.item_name, f.item_code, s.store_sum"
                 " having sum(f.qty) > s.store_sum");
    qro->bindValue(":clinic_code", patientInfo["CLINIC_CODE"] );

    qro->exec();

    //是否存在申请数量是否超过库存数量的记录
    while(qro->next()){
        QMessageBox::information(this,"注意", qro->value(1).toString() + " 申请数量大于库存数量，处方无法执行！");
        stop = true;
    }
    if(stop) return;//出现过无效记录


    //计算发票收费分类, 分类方法：执行科室 + 费用类别
    qDebug()<<"计算发票收费分类";

    qro->exec("select (select fee_stat_name from FIN_COM_FEECODESTAT "
              " where rownum = '1' and report_code='MZ01' and fee_code = f.fee_code) fee_name, fee_code,"
              " exec_dpcd, exec_dpnm, sum(own_cost) own_cost "
              " from fin_opb_feedetail f"
              " where clinic_code = '" + patientInfo["CLINIC_CODE"] + "' and pay_flag <>'1'"
                                                                      " group by exec_dpcd, fee_code, exec_dpnm order by exec_dpcd,fee_code");

    lstFeeType.clear();

    double countFeeList = 0;   //对 fin_opb_feedetail 金额进行累计

    while(qro->next()){
        mp["fee_name"] = qro->value("fee_name").toString();
        mp["fee_code"] = qro->value("fee_code").toString();
        mp["dept_code"] = qro->value("exec_dpcd").toString();
        mp["dept_name"] = qro->value("exec_dpnm").toString();
        mp["own_cost"] = QString::asprintf("%.2f", qro->value("own_cost").toDouble());
        mp["invoice_no"] = "invoice_no";
        countFeeList += qro->value("own_cost").toDouble();
        lstFeeType << mp;
    }
    mp.clear();

    double countItemDetail = 0;   //对 lstItemDetail 金额进行累计
    foreach(mp, lstItemDetail){

        countItemDetail += mp["RETAIL_PRICE"].toDouble() * mp["APPLY_NUM"].toDouble() / mp["PACK_QTY"].toDouble();

    }

    if( !qFuzzyCompare(countFeeList, countItemDetail)){       //前后结果不相等
        QMessageBox::information(this,"注意", " 汇总金额与明细金额累计不符！");
        return;

    }

    mp.clear();

    QString execDeptCode = "";
    QString invoice_no, invoice_seq;
    QString invoices = "'invoice'";    //便于算法书写，无特殊意义
    idx = 0;

    //申请发票号，写入 fin_opb_invoicedetail
    qDebug()<<"发票明细表(费用分类表)";
    foreach(mp, lstFeeType){
        //执行科室变更，申请新发票号
        if(execDeptCode != mp["dept_code"]){
            execDeptCode = mp["dept_code"];
            char errorText[128];
            for(int i = 0; i<128; i++){
                errorText[i] = '0';
            }
            char fpChar[12];
            for(int i = 0; i<12; i++){
                fpChar[i] = '0';
            }

            int errorCode = 0;
            QString a,b,c;

            qro->prepare("call prc_get_invoiceno('C', :oper, 50, :ivno, :errtext, :errcode, '')");
            qro->bindValue(":oper", pub::usr_code );//操作员Id
            qro->bindValue(":ivno", fpChar, QSql::Out);   //发票号码
            qro->bindValue(":errtext", errorText, QSql::Out);   //错误内容
            qro->bindValue(":errcode", errorCode, QSql::Out);    //错误编号
            qro->exec();

            a = qro->boundValue(":ivno").toString();
            b = qro->boundValue(":errtext").toString();
            c = qro->boundValue(":errcode").toString();

            if( a.isEmpty()){
                QMessageBox::information(this,"错误", "申请发票号失败：" + b );
                return;
            }
            if(c == "101"){
                QMessageBox::information(this,"注意", "未用发票数量低，请及时请领！" );
            }
            invoice_no = a;//发票号
            invoices = invoices + ",'" + a + "'";

            qro->exec("select seq_fin_opb_invoice.nextval from dual");
            qro->next();
            invoice_seq = qro->value(0).toString();
            if(invoice_seq.isEmpty()){
                QMessageBox::information(this,"注意", "seq_fin_opb_invoice.nextval 返回失败！" );
                return;
            }
        }

        //发票明细表(费用分类表)
        qro->prepare("Insert into fin_opb_invoicedetail "
                     "(INVOICE_NO,TRANS_TYPE,INVO_CODE,INVO_SEQUENCE,INVO_NAME,PUB_COST,"
                     "OWN_COST,PAY_COST,DEPT_CODE,DEPT_NAME,OPER_DATE,"
                     "OPER_CODE,BALANCE_FLAG,BALANCE_NO,BALANCE_OPCD,"
                     "BALANCE_DATE,CANCEL_FLAG,INVOICE_SEQ)"
                     " Values"
                     " (:INVOICE_NO,'1',:INVO_CODE,:INVO_CODE,:INVO_NAME,0,"
                     " :OWN_COST,0,:DEPT_CODE,:DEPT_NAME,sysdate, :OPER_CODE,'0','','',"
                     " to_date('0001/1/1','yyyy-mm-dd'),'1',:INVOICE_SEQ)  ");
        qro->bindValue(":INVOICE_NO", invoice_no);
        qro->bindValue(":INVO_CODE", mp["fee_code"].right(2));
        qro->bindValue(":INVO_NAME", mp["fee_name"]);
        qro->bindValue(":DEPT_CODE", mp["dept_code"]);
        qro->bindValue(":DEPT_NAME", mp["dept_name"]);
        qro->bindValue(":OWN_COST", mp["own_cost"]);
        qro->bindValue(":OPER_CODE", pub::usr_code);
        qro->bindValue(":INVOICE_SEQ", invoice_seq);

        lstFeeType[idx]["invoice_no"] = invoice_no; //补齐发票号，为后续算法方便
        idx ++;

        if(!qro->exec()){
            QMessageBox::information(this,"注意", "插入 fin_opb_invoicedetail 失败！"+qro->lastError().text() );
            qDebug()<<qro->lastQuery();
            qDebug()<<invoice_no<<mp["fee_code"].right(2)<< mp["fee_name"]<<mp["dept_code"]<<mp["dept_name"]
                   <<mp["own_cost"]<<pub::usr_code<<invoice_seq;
            return;
        }
        qDebug()<<qro->lastQuery();
        qDebug()<<invoice_no<<mp["fee_code"].right(2)<< mp["fee_name"]<<mp["dept_code"]<<mp["dept_name"]
               <<mp["own_cost"]<<pub::usr_code<<invoice_seq;
    }

    mp.clear();

    lstInvoiceInfo.clear();

    //患者一次结算产生多张发票，使用同一个 BALANCE_COMBONO
    qro->exec("select seq_fin_opb_balancecombono.nextval from dual");
    qro->next();
    patientInfo["BALANCE_COMBONO"] = qro->value(0).toString();

    qro->exec("select invoice_no, invoice_seq, dept_name, sum(own_cost) ocst, dept_code "
              " from fin_opb_invoicedetail where invoice_no in(" + invoices + ") "
                                                                              " group by invoice_no, invoice_seq, dept_name,dept_code");

    while(qro->next()){
        mp["invoice_no"] = qro->value(0).toString();
        mp["invoice_seq"] = qro->value(1).toString();
        mp["dept_name"] = qro->value(2).toString();
        mp["ocst"] = QString::asprintf("%.2f",qro->value(3).toDouble());
        mp["dept_code"] = qro->value(4).toString();

        qro2->exec("select ext_flag from com_department where dept_code = '"+mp["dept_code"]+"'");
        qro2->next();
        QString p = qro2->value(0).toString();
        mp["printItem"] = p;

        //根据执行科室为 lstItemDetail 补齐发票号内容
        //bool hasInsu;   //有医保项目
        mp["has_insu"] = "0";  //预置发票无医保内容
        for(int id = 0; id<lstItemDetail.length(); id ++){
            if(lstItemDetail[id]["DRUG_DEPT_CODE"] == mp["dept_code"]){
                lstItemDetail[id]["invoice_no"] = mp["invoice_no"];
                lstItemDetail[id]["invoice_seq"] = mp["invoice_seq"];
                if(lstItemDetail[id]["has_compare"] == "1"){
                    mp["has_insu"] = "1";//此发票有医保内容
                }
            }
        }

        //按现金操作预置
        mp["real_cost"] = mp["ocst"];
        mp["own_cost"] = mp["ocst"];
        mp["tot_cost"] = mp["ocst"];
        mp["pay_cost"] = "";
        //
        lstInvoiceInfo << mp;

    }

    qDebug()<<"lstFeeType"<<lstFeeType;
    qDebug()<<"lstItemDetail"<<lstItemDetail;
    qDebug()<<"lstInvoiceInfo"<<lstInvoiceInfo;
    //return;

    mp.clear();

    if( patientInfo["yb"] == "1"){  //本次操作是医保结算
        //保存医保相关数据
        tmString = "进行医保结算数据";
        //tm->start(400);
        ui->lbMode->setText(tmString);
        qApp->processEvents();  //刷新显示
        foreach ( mp, lstInvoiceInfo ){
            if(mp["has_insu"] == "0"){  //此发票无医保内容
                continue;
            }
            patientInfo["Dept_Code"] = mp["dept_code"]; //saveSi需要此值
            patientInfo["Dept_Name"] = mp["dept_name"]; //saveSi需要此值
            if(!saveSI(mp["invoice_no"])){
                //tm->stop();
                //医保操作失败，清理已经发生的数据。
                qro->exec("delete from fin_opb_invoicedetail "
                          "where INVOICE_NO in (" + invoices + ")");
                qDebug()<<"delete from fin_opb_invoicedetail rows "<<qro->numRowsAffected();
                QString iv_start = pub::getStr(invoices,"','",2);
                iv_start = iv_start.left(12);   //最后一个发票号会有单引号结尾，需要限制长度
                qDebug()<<"iv_start"<<iv_start;
                sq = "select start_no, end_no from fin_com_invoice "
                     " where get_person_code = '" + pub::usr_code + "' and used_state = '1' "
                                                                    " and invoice_kind = 'C' ";
                if(!qro->exec(sq)){
                    qDebug()<<qro->lastError().text();
                    qDebug()<<qro->lastQuery();
                    return;
                }
                if(!qro->next()){
                    return;
                }
                QString str_start = qro->value(0).toString();
                QString str_end = qro->value(1).toString();
                int start = str_start.toInt();
                int end = str_end.toInt();
                int cur = iv_start.toInt();
                qDebug()<<"start end number is "<<start<<end;

                if(start < cur && cur < end){  //号码在当前使用范围内
                    cur = cur - 1;
                    qDebug()<<"cur"<<cur;
                    QString str_cur = QString::number(cur);
                    qDebug()<<pub::add0(str_cur,12);
                    sq = "update fin_com_invoice set used_no = '" + pub::add0(str_cur,12) + "' "
                                                                                            "where get_person_code = '" + pub::usr_code + "' and used_state = '1' "
                                                                                                                                          "and invoice_kind = 'C' and start_no = '" + str_start + "' "
                                                                                                                                                                                                  "and end_no = '" +str_end + "'";
                    if(!qro->exec(sq)){
                        qDebug()<<qro->lastError().text();
                        qDebug()<<qro->lastQuery();

                        return;
                    }
                }
                return;
            }
        }
        //tm->stop();
    }

    mp.clear();

    //发票信息表(结算信息表)
    qDebug()<<"发票信息表(结算信息表)";
    int printInvoiceno = invoice_no.toInt();

    idx = 0;
    ui->lbMode->setText("保存发票信息");
    qApp->processEvents();  //刷新显示

    foreach(mp, lstInvoiceInfo){
        qro->prepare("Insert into fin_opb_invoiceinfo"
                     " (INVOICE_NO,TRANS_TYPE,CARD_NO,REG_DATE,NAME,PAYKIND_CODE,"
                     " PACT_CODE,PACT_NAME,MCARD_NO,MEDICAL_TYPE,TOT_COST,PUB_COST,OWN_COST,"
                     " PAY_COST,BACK1,BACK2,BACK3,REAL_COST,OPER_CODE,"
                     " OPER_DATE,EXAMINE_FLAG,CANCEL_FLAG,CHECK_FLAG,BALANCE_FLAG,"
                     " INVOICE_SEQ,CLINIC_CODE,PRINT_INVOICENO,DRUG_WINDOW,"
                     " ACCOUNT_FLAG,BALANCE_COMBONO)"
                     " Values"
                     " (:INVOICE_NO,'1',:CARD_NO,:REG_DATE,:NAME,:PAYKIND_CODE,"
                     " :PACT_CODE,:PACT_NAME,:MCARD_NO,:MEDICAL_TYPE,:TOT_COST,0,:OWN_COST,"
                     " :PAY_COST,'0','','',0,:OPER_CODE, sysdate,'0','1','0','0',"
                     " :INVOICE_SEQ,:CLINIC_CODE,:PRINT_INVOICENO,"
                     " :DRUG_WINDOW,'0',:BALANCE_COMBONO)");

        qro->bindValue(":CARD_NO", patientInfo["CARD_NO"]);
        QDateTime dt = QDateTime::fromString(patientInfo["REG_DATE"],"yyyy-MM-dd hh:mm:ss") ;
        qro->bindValue(":REG_DATE", dt);
        qro->bindValue(":NAME", patientInfo["PATIENT_NAME"]);
        qro->bindValue(":PAYKIND_CODE", patientInfo["PAYKIND_CODE"]);
        qro->bindValue(":PACT_CODE", patientInfo["PACT_CODE"]);
        qro->bindValue(":PACT_NAME", patientInfo["PACT_NAME"]);
        qro->bindValue(":MCARD_NO", patientInfo["MCARD_NO"]);
        qro->bindValue(":MEDICAL_TYPE", patientInfo["MEDICAL_TYPE"]);
        qro->bindValue(":CLINIC_CODE",patientInfo["CLINIC_CODE"]);
        qro->bindValue(":OPER_CODE", pub::usr_code);
        qro->bindValue(":INVOICE_NO", mp["invoice_no"]);
        qro->bindValue(":TOT_COST", mp["ocst"]);
        qro->bindValue(":OWN_COST", mp["own_cost"]);
        qro->bindValue(":PAY_COST", mp["pay_cost"]);
        qro->bindValue(":INVOICE_SEQ", mp["invoice_seq"]);
        qro->bindValue(":PRINT_INVOICENO", QString::number(printInvoiceno));
        qro->bindValue(":DRUG_WINDOW", mp["dept_name"]);
        qro->bindValue(":BALANCE_COMBONO",patientInfo["BALANCE_COMBONO"]);
        if(!qro->exec()){
            QMessageBox::information(this,"注意", "插入 fin_opb_invoiceinfo 失败！"+qro->lastError().text() );
        }

        //东软系统流程逻辑：只对单纯现金收费做四舍五入记录，对医保余额不足需要缴纳现金不做记录。
        //本系统变更为：只要涉及到现金四舍五入，全都进行记录。
        //多张发票四舍五入结果相互调剂
        //通过POS机支付的现金不需要四舍五入

        if(balanceFlag){   //需要四舍五入
            qro->prepare("Insert into fin_opb_paymode"
                         "(INVOICE_NO,TRANS_TYPE,SEQUENCE_NO,MODE_CODE,TOT_COST,REAL_COST, OPER_CODE,"
                         "OPER_DATE,CHECK_FLAG,CHECK_OPCD,BALANCE_FLAG,BALANCE_NO,BALANCE_OPCD,CORRECT_FLAG,"
                         " CORRECT_OPCD,INVOICE_SEQ,CANCEL_FLAG,postrans_no ,MEMO,balance_combono )"
                         " Values "
                         "(:INVOICE_NO,'1',:SEQUENCE_NO,'CA',:TOT_COST,:REAL_COST, :OPER_CODE,sysdate,'0',"
                         "'','0','','','0','',:INVOICE_SEQ,'1','' ,'',:balance_combono)"
                         );
            qro->bindValue(":INVOICE_NO", mp["invoice_no"]);
            qro->bindValue(":SEQUENCE_NO", QString::number(balanceSeq));
            qro->bindValue(":OPER_CODE", pub::usr_code);
            qro->bindValue(":INVOICE_SEQ", mp["invoice_seq"]);
            qro->bindValue(":balance_combono", patientInfo["BALANCE_COMBONO"]);
            qro->bindValue(":TOT_COST", mp["ocst"]);
            double t = mp["own_cost"].toDouble();
            double t45 = QString::asprintf("%.1f",t).toDouble();
            if( !qFuzzyCompare(t, t45)){       //四舍五入前后结果不相等，进行补偿计算
                t = t + balance;    //对每张发票的差额进行累计补偿
                t45 = QString::asprintf("%.1f",t).toDouble();   //累计之后的本张发票实收额
                balance = t - t45;  //新的累计差额
            }

            qro->bindValue(":REAL_COST", t45);

            if(!qro->exec()){
                qDebug()<<qro->lastError().text();
                qDebug()<<qro->lastQuery();
            }
            lstInvoiceInfo[idx]["real_cost"] = QString::asprintf("%.1f", t45);
            balanceSeq ++;
        }
        idx++;
        printInvoiceno ++;
    }

    //保存当前工作发票号
    qro->exec("update COM_DICTIONARY set name='" + QString::number(printInvoiceno) +
              "', mark='" + mp["invoice_no"] + "', oper_Date = sysdate "
                                               " where type ='MZINVOICE' and code ='" + pub::usr_code + "'");
    mp.clear();

    //写入pha_com_applyout, 补全 fin_opb_feedetail
    qDebug()<<"写入pha_com_applyout, 补全 fin_opb_feedetail";

    stop = false;   //循环结束之后的退出标志

    ui->lbMode->setText("保存收费明细");
    qApp->processEvents();  //刷新显示

    idx = 0;       //循环索引，控制循环结束使用
    QString applyNumbers = "0";    //保存写入到pha_com_applyout中的 apply_number
    foreach(mp, lstItemDetail){
        idx ++;
        //写入 fin_opb_feedetail 数据
        ui->lbMode->setText("保存收费明细-fin_opb_feedetail");
        qApp->processEvents();  //刷新显示

        qDebug()<<"写入 fin_opb_feedetail 数据";
        qro->prepare("update fin_opb_feedetail set center_code = :center_code, item_grade = :item_grade ,"
                     " pay_flag = '1', fee_cpcd = :fee_cpcd, fee_date = sysdate, invoice_no = :invoice_no,"
                     " invoice_seq = :invoice_seq, new_itemrate = :new_itemrate, old_itemrate = :old_itemrate,"
                     " ext_flag = '1', over_cost = unit_price"
                     " where pay_flag = '0' and clinic_code = :clinic_code and exec_dpcd = :dpcd and item_code = :itmcd "
                     );
        qro->bindValue(":center_code", mp["center_code"]);
        qro->bindValue(":item_grade", mp["center_item_grade"]);
        qro->bindValue(":new_itemrate", mp["center_rate"]);
        qro->bindValue(":fee_cpcd", mp["DEPT_CODE"]);
        qro->bindValue(":invoice_no", mp["invoice_no"]);
        qro->bindValue(":invoice_seq", mp["invoice_seq"]);
        qro->bindValue(":itmcd", mp["item_code"]);
        if(patientInfo["yb"] == "1" ){ //医保交易和现金交易此字段值有区别
            qro->bindValue(":old_itemrate", "0");
        }else{
            qro->bindValue(":old_itemrate", "1");
        }
        qro->bindValue(":clinic_code", patientInfo["CLINIC_CODE"]);
        qro->bindValue(":dpcd", mp["DRUG_DEPT_CODE"]);
        if(!qro->exec()){
            QMessageBox::information(this,"错误", "update fin_opb_feedetail 失败！"+qro->lastError().text());
            qDebug()<<qro->lastError().text();
            qDebug()<<qro->lastQuery();

            qDebug()<<":center_code"<< mp["center_code"];
            qDebug()<<":item_grade"<< mp["center_item_grade"];
            qDebug()<<":new_itemrate"<< mp["center_rate"];
            qDebug()<<":fee_cpcd"<< mp["DEPT_CODE"];
            qDebug()<<":invoice_no"<< mp["invoice_no"];
            qDebug()<<":invoice_seq"<< mp["invoice_seq"];
            qDebug()<<":itmcd"<< mp["item_code"];
            qDebug()<<":old_itemrate"<< "0";
            qDebug()<<":clinic_code"<< patientInfo["CLINIC_CODE"];
            qDebug()<<":dpcd"<< mp["DRUG_DEPT_CODE"];
            return;
        }
        ui->lbMode->setText("保存收费明细-met_ord_recipedetail");
        qApp->processEvents();
        qDebug()<<"写入 met_ord_recipedetail 数据";
        qro->prepare("update met_ord_recipedetail set charge_flag ='1' , status ='1' ,"
                     " charge_code = :charge_code, charge_date = sysdate"
                     " where sequence_no = :sequence_no and status='0'"
                     );
        qro->bindValue(":charge_code", pub::usr_code);
        qro->bindValue(":sequence_no", mp["MO_ORDER"]);
        if(!qro->exec()){
            QMessageBox::information(this,"错误", "写入 met_ord_recipedetail 失败！"+qro->lastError().text());
            qDebug()<<qro->lastQuery();
            return;
        }

        //如果非药品，跳过写入 pha_com_applyout 过程
        if(mp["drug_flag"] == "0"){
            qDebug()<<"非药品";
            continue;
        }
        qro->exec("select seq_pha_applyout_id.nextval from dual");
        qro->next();
        QString apply_num = qro->value(0).toString();
        applyNumbers.append("," + apply_num );
        ui->lbMode->setText("保存收费明细-pha_com_applyout");
        qApp->processEvents();
        qro->prepare("INSERT INTO PHA_COM_APPLYOUT (APPLY_NUMBER ,DEPT_CODE ,DRUG_DEPT_CODE ,"
                     "CLASS3_MEANING_CODE , GROUP_CODE ,DRUG_CODE ,TRADE_NAME ,BATCH_NO ,"
                     "DRUG_TYPE ,DRUG_QUALITY, SPECS , PACK_UNIT , PACK_QTY , MIN_UNIT , "
                     "SHOW_FLAG , SHOW_UNIT , RETAIL_PRICE ,WHOLESALE_PRICE ,PURCHASE_PRICE ,"
                     "APPLY_OPERCODE ,APPLY_DATE ,APPLY_STATE , APPLY_NUM ,DAYS ,"
                     "PREOUT_FLAG ,CHARGE_FLAG ,PATIENT_ID ,PATIENT_DEPT ,DOSE_ONCE ,"
                     "DOSE_UNIT ,USAGE_CODE ,USE_NAME ,DFQ_FREQ ,DFQ_CEXP ,DOSE_MODEL_CODE,"
                     "MO_ORDER ,COMB_NO  , RECIPE_NO ,SEQUENCE_NO,SEND_TYPE,BILLCLASS_CODE,"
                     "PRINT_STATE,OUT_BILL_CODE,VALID_STATE,MARK,PLACE_CODE) "
                     " VALUES "
                     "( :apply_num, :DEPT_CODE ,:DRUG_DEPT_CODE ,'M1' , '0' ,:DRUG_CODE ,"
                     ":TRADE_NAME ,'' ,:DRUG_TYPE ,:DRUG_QUALITY, :SPECS , :PACK_UNIT ,:PACK_QTY ,"
                     ":MIN_UNIT , '0' , '', :RETAIL_PRICE ,0 ,0 ,:APPLY_OPERCODE ,sysdate ,'0' ,"
                     ":APPLY_NUM ,:DAYS ,'0' ,'1' ,:PATIENT_ID ,:PATIENT_DEPT ,:DOSE_ONCE ,"
                     ":DOSE_UNIT ,:USAGE_CODE , :USE_NAME ,:DFQ_FREQ ,"
                     "(select frequency_name from MET_COM_DEPTFREQUENCY "
                     " where rownum = '1' and frequency_code = :DFQ_FREQ ),:DOSE_MODEL_CODE,"
                     ":MO_ORDER ,:COMB_NO , :RECIPE_NO ,:SEQUENCE_NO,'0','','',0,'1','','') ");

        qro->bindValue(":apply_num", apply_num );
        qro->bindValue(":DEPT_CODE", mp["DEPT_CODE"] );
        qro->bindValue(":DRUG_DEPT_CODE", mp["DRUG_DEPT_CODE"] );
        qro->bindValue(":DRUG_CODE", mp["item_code"] );
        qro->bindValue(":TRADE_NAME", mp["TRADE_NAME"] );
        qro->bindValue(":DRUG_TYPE", mp["DRUG_TYPE"] );
        qro->bindValue(":DRUG_QUALITY", mp["DRUG_QUALITY"] );
        qro->bindValue(":SPECS", mp["SPECS"] );
        qro->bindValue(":PACK_UNIT", mp["PACK_UNIT"] );
        qro->bindValue(":PACK_QTY", mp["PACK_QTY"] );
        qro->bindValue(":MIN_UNIT", mp["MIN_UNIT"] );
        qro->bindValue(":RETAIL_PRICE", mp["RETAIL_PRICE"] );
        qro->bindValue(":APPLY_OPERCODE",pub::usr_code);
        qro->bindValue(":APPLY_NUM", mp["APPLY_NUM"] );
        qro->bindValue(":DAYS", mp["DAYS"] );
        qro->bindValue(":PATIENT_ID", mp["PATIENT_ID"] );
        qro->bindValue(":PATIENT_DEPT", mp["PATIENT_DEPT"] );
        qro->bindValue(":DOSE_ONCE", mp["DOSE_ONCE"] );
        qro->bindValue(":DOSE_UNIT", mp["DOSE_UNIT"] );
        qro->bindValue(":USAGE_CODE", mp["USAGE_CODE"] );
        qro->bindValue(":USE_NAME", mp["USE_NAME"] );
        qro->bindValue(":DFQ_FREQ", mp["DFQ_FREQ"] );
        qro->bindValue(":DOSE_MODEL_CODE", mp["DOSE_MODEL_CODE"] );
        qro->bindValue(":MO_ORDER", mp["MO_ORDER"] );
        qro->bindValue(":COMB_NO", mp["COMB_NO"] );
        qro->bindValue(":RECIPE_NO", mp["RECIPE_NO"] );
        qro->bindValue(":SEQUENCE_NO", mp["SEQUENCE_NO"] );
        if(!qro->exec()){
            QMessageBox::information(this,"错误", "写入 pha_com_applyout 失败！"+qro->lastError().text());
            qDebug()<<qro->lastQuery();
            return;
        }

    }
    ui->lbMode->setText("保存处方信息");
    qApp->processEvents();  //刷新显示

    sq = "select recipe_no, drug_dept_code, dept_code, count(recipe_no), sum(apply_num / pack_qty * retail_price)"
         " from pha_com_applyout where apply_number in(" + applyNumbers + ") group by recipe_no,drug_dept_code,dept_code";

    if(!qro2->exec(sq)){
        QMessageBox::information(this,"错误", "从 pha_com_applyout 提取数据失败！"+qro2->lastError().text());
        qDebug()<<qro2->lastQuery();
        return;
    }

    mp.clear();
    QString doc_dpt, doc_cod,ivno;
    while(qro2->next()){

        ivno = "";
        doc_dpt = "";
        doc_cod = "";
        foreach(mp, lstItemDetail){ //提取关联信息
            if( mp["DRUG_DEPT_CODE"] ==  qro2->value(1).toString()){
                doc_cod = mp["doct_code"] ;
                doc_dpt = mp["doct_dept"] ;
                ivno = mp["invoice_no"];
                break;
            }
        }
        if(ivno.isEmpty()){
            QMessageBox::information(this,"错误", "写入 pha_sto_recipe 时提取发票号失败！");
            return;
        }

        qDebug()<<"写入 PHA_STO_RECIPE 数据";
        qro->prepare("INSERT INTO PHA_STO_RECIPE "
                     "(DRUG_DEPT_CODE, RECIPE_NO, CLASS3_MEANING_CODE, TRANS_TYPE, RECIPE_STATE,"
                     "CLINIC_CODE, CARD_NO, PATIENT_NAME, SEX_CODE, BIRTHDAY, PAYKIND_CODE, DEPT_CODE,"
                     "REG_DATE, DOCT_CODE, DOCT_DEPT, DRUGED_TERMINAL, SEND_TERMINAL, FEE_OPER, FEE_DATE,"
                     "INVOICE_NO, RECIPE_COST, RECIPE_QTY, DRUGED_QTY, DRUGED_OPER, DRUGED_DEPT,"
                     "DRUGED_DATE, SEND_DATE, SEND_DEPT, VALID_STATE, MODIFY_FLAG, MARK, SUM_DAYS )"
                     " VALUES "
                     "(:DRUG_DEPT_CODE,:RECIPE_NO, 'M1', '1', '0', :CLINIC_CODE, :CARD_NO, :PATIENT_NAME,"
                     ":SEX_CODE, :BIRTHDAY, :PAYKIND_CODE, :DEPT_CODE, :REG_DATE, :DOCT_CODE, :DOCT_DEPT,"
                     "(select t_code from pha_sto_terminal where rownum = '1' and dept_code = :DRUG_DEPT_CODE and t_type = '1' ),"
                     "(select t_code from pha_sto_terminal where rownum = '1' and dept_code = :DRUG_DEPT_CODE and t_type = '0' ), "
                     ":FEE_OPER, sysdate, :INVOICE_NO, :RECIPE_COST, :RECIPE_QTY,"
                     ":DRUGED_QTY, :DRUGED_OPER, :DRUG_DEPT_CODE, sysdate, sysdate, :DRUG_DEPT_CODE, '1',"
                     "'0', 'c', :SUM_DAYS )"
                     );

        qro->bindValue(":DRUG_DEPT_CODE", qro2->value(1).toString());
        qro->bindValue(":RECIPE_NO", qro2->value(0).toString());
        qro->bindValue(":CLINIC_CODE", patientInfo["CLINIC_CODE"]);
        qro->bindValue(":CARD_NO", patientInfo["CARD_NO"]);
        qro->bindValue(":PATIENT_NAME", patientInfo["PATIENT_NAME"]);
        qro->bindValue(":SEX_CODE", patientInfo["SEX_CODE"]);
        QDateTime dt = QDateTime::fromString(patientInfo["BIRTHDAY"],"yyyy-MM-dd") ;
        qro->bindValue(":BIRTHDAY", dt);
        qro->bindValue(":PAYKIND_CODE", patientInfo["PAYKIND_CODE"]);
        qro->bindValue(":DEPT_CODE",  qro2->value(2).toString());
        dt = QDateTime::fromString(patientInfo["REG_DATE"],"yyyy-MM-dd hh:mm:ss") ;
        qro->bindValue(":REG_DATE", dt);
        qro->bindValue(":DOCT_CODE", doc_cod);
        qro->bindValue(":DOCT_DEPT", doc_dpt);
        qro->bindValue(":FEE_OPER", pub::usr_code);
        qro->bindValue(":INVOICE_NO", ivno);
        qro->bindValue(":RECIPE_COST", qro2->value(4).toDouble());
        qro->bindValue(":RECIPE_QTY",  qro2->value(3).toInt());
        qro->bindValue(":DRUGED_QTY", 0);
        qro->bindValue(":DRUGED_OPER", "");
        qro->bindValue(":SUM_DAYS",  qro2->value(3).toInt());
        if(!qro->exec()){
            QMessageBox::information(this,"错误", "写入 pha_sto_recipe 失败！"+qro->lastError().text());
            qDebug()<<qro->lastQuery();
            return;
        }
    }//qro2
    mp.clear();
    ui->lbMode->setText("打印发票");
    qApp->processEvents();  //刷新显示

    on_pbPrint_clicked();
    ui->pbPrint->setEnabled(true);
    if(ui->cbAutoFlash->isChecked()){
        on_pbSx_clicked();          //
    }
}

QString Form_sk::getDoctCode(QString s)
{
    //检索发票关联的医生
    QString ret = "";
    QMap<QString,QString>m;
    QStringList retList;
    foreach(m, lstItemDetail){
        if(m["invoice_no"] == s){
            retList << m["doct_code"];
        }
    }
    retList.removeDuplicates();
    foreach(QString s, retList){
        if(ret.isEmpty()){  //
            ret = s;
        }else{
            ret = ret + "," + s ;
        }

    }
    return ret;
}

QStringList Form_sk::getFeeTypes(QString s)
{
    //检索发票关联的费别
    QStringList ret ;
    QMap<QString,QString>m;
    foreach(m, lstFeeType){
        if(m["invoice_no"] == s){
            ret << m["fee_name"] + " : " + m["own_cost"];
        }
    }

    return ret;
}

QStringList Form_sk::getItems(QString s)
{
    //检索发票关联的项目明细
    QStringList ret ;
    QMap<QString,QString>m;
    foreach(m, lstItemDetail){
        if(m["invoice_no"] == s){
            ret << m["TRADE_NAME"] + "^" + m["SPECS"] + "^" +
                    QString::number(m["APPLY_NUM"].toInt() / m["PACK_QTY"].toInt())
                    + "^" + m["RETAIL_PRICE"];
        }
    }
    return ret;
}

QString Form_sk::getInvoiceNo(QString s)
{
    //检索科室关联的发票号
    QString ret = "";
    QMap<QString,QString>m;

    foreach(m, lstInvoiceInfo){
        if(m["dept_code"] == s){
            return m["invoice_no"] + "^" + m["invoice_seq"];
        }
    }
    return ret;
}

void Form_sk::on_pbYbjs_clicked()   //医保预结算
{

//    if(noneInsuItem){
//        QMessageBox::information(this,"note","列表中存在非医保项目，无法使用医保结算。");
//        return;
//    }

    ui->pbYbjs->setEnabled(false);//正常情况下，预结算只需要操作一次
    if(!hasInsuItem){
        QMessageBox::information(this,"note","列表中没有医保项目，无法使用医保结算。");
        return;
    }

    //预置医保结算失败之后的状态。如果医保预结算成功，此状态会被修改
    ui->pbSfbc->setEnabled(false);  //医保预结算期间禁止操作

    qApp->processEvents();
    ui->lbMode->setText("收费方式：现金 、POS机");
    patientInfo["PAYKIND_CODE"] = "01";
    patientInfo["PACT_CODE"] = "1";
    patientInfo["PACT_NAME"] = "现金";
    ui->rbX->setChecked(true);
    tm->start(500);
    if(ybyjs()){
        QMessageBox::information(this,"note","预结算成功！");
        if(mdtrt_cert_type == "03"){    //医保模式
            ui->lbMode->setText("收费方式：沈阳市医保，刷卡支付");

        }else if(mdtrt_cert_type == "01"){
            ui->lbMode->setText("收费方式：沈阳市医保，电子医保二维码");

        }else if(mdtrt_cert_type == "02"){
            ui->lbMode->setText("收费方式：沈阳市医保，身份证方式");
        }
    }else{
        ui->pbYbjs->setEnabled(true);//预结算不成功，可以再次尝试
    }
    ui->pbSfbc->setEnabled(true);  //医保预结算结束
    //
    tm->stop();
}

bool Form_sk::ybyjs()
{
    //医保信息住院主表，查询当前流水号，检查是否使用医保挂号
    statusMsg = "检索基础数据。。。";

    if(!searchBaseData()){
        return false;
    }

    statusMsg = "医保状态有效性验证。。。";

    //卡机开始读卡
    int mod = mdtrt_cert_type.toInt();

    QJsonDocument d;    //清空QJsonObject之用
    QJsonObject in; //入参
    QJsonObject inpu,inpud; // 入参 input 段
    QJsonDocument indoc;

    QString sfzh;//身份证号
    qDebug()<<"mod"<<mod;
    if(mod == 1){

        if(!scanCode()){
            return false;
        }

        inpu.insert("mdtrt_cert_type", mdtrt_cert_type);   //就诊凭证类别
        inpu.insert("mdtrt_cert_no", retScan.value("ecToken").toString());   //token
        inpu.insert("psn_name", retScan.value("userName").toString()); //人员姓名
        //inpu.insert("card_sn", retScan.value("ecToken").toString()); //卡识别码
        inpu.insert("certno", retScan.value("idNo").toString() );      //证件号码
        inpu.insert("psn_cert_type","01");       //人员证件类型  固定？
        //        sfzh = retScan.value("idNo").toString();

    }else if(mod == 2){

        if(!readIdCard()){
            return false;
        }
        inpu.insert("mdtrt_cert_type", mdtrt_cert_type);   //就诊凭证类别
        inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",2) + "|" + busiCardInfo);   //社保卡,4卡号3社保号
        inpu.insert("psn_name", pub::getStr(cardInfo,"|",5)); //人员姓名
        inpu.insert("certno", pub::getStr(cardInfo,"|",2));      //证件号码
        inpu.insert("psn_cert_type","01");       //人员证件类型  固定？
         sfzh = pub::getStr(cardInfo,"|",2);

    }else if(mod == 3){

        if(!readCard()){
            return false;
        }
        //emit opThread( mod , "QString");    // 发送信号触发线程 , 执行 ReadCardBas
        inpu.insert("mdtrt_cert_type", mdtrt_cert_type);   //就诊凭证类别
        if( "1" == pub::getStr(cardInfo,"|",1) ){   //0 社保卡， 1 老医保卡
            if(pub::getStr(cardInfo,"|",8).isEmpty()){
                inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",9) + "|" + busiCardInfo);//老医保卡,8卡号9社保号
            }else{
                inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",8) + "|" + busiCardInfo);//老医保卡,8卡号9社保号
            }
            //sfzh = pub::getStr(cardInfo,"|",9);
            inpu.insert("psn_name", pub::getStr(cardInfo,"|",10)); //人员姓名
            inpu.insert("card_sn",pub::getStr(cardInfo,"|",2)); //卡识别码
            inpu.insert("certno", pub::getStr(cardInfo,"|",9));      //证件号码
            inpu.insert("psn_cert_type","01");       //人员证件类型  固定？
        }else{
            inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",4) + "|" + busiCardInfo);   //社保卡,4卡号3社保号
            inpu.insert("psn_name", pub::getStr(cardInfo,"|",6)); //人员姓名
            inpu.insert("card_sn",pub::getStr(cardInfo,"|",5)); //卡识别码
            inpu.insert("certno", pub::getStr(cardInfo,"|",3));      //证件号码
            inpu.insert("psn_cert_type","01");       //人员证件类型  固定？
            //sfzh = pub::getStr(cardInfo,"|",3);
        }

    }

    statusMsg = "1100 获取人员信息。。。";
    //1100开始获取人员信息
    in = d.object();

    if(!putBaseIn(  in, "1101")){

        return false;
    }
    inpud.insert("data",inpu);
    in.insert("input", inpud);

    //    QJsonDocument indoc ;
    indoc.setObject(in);

    //保存入参日志
    qDebug()<< currentInfno + " indoc"<<indoc;
    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact) + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    QNetworkReply* reply = manager.post(request,indoc.toJson());
    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。

    qDebug()<<" request " + currentInfno + " is returned ";

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意", currentInfno + " http 请求状态错误: " + statusCode.toString());

        return false ;
    }

    QNetworkReply::NetworkError err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());

        return false ;
    }

    QByteArray btret = reply->readAll();
    QString t = QString::fromLocal8Bit(btret);

    QJsonParseError json_error;

    QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意", currentInfno + " 返回信息解析错误 " + json_error.errorString());

        return false ;
    }
    qDebug()<< currentInfno + " outDoc "<<jsdc;
    QJsonObject jsob = jsdc.object();

    //保存出出参日志

    sq = "update com_business set v_out = '"
            + jsdc.toJson(QJsonDocument::Compact) + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }

    if(jsob.value("infcode").toInt() != 0){
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意", currentInfno + " 交易失败：" + t );

        return false ;
    }

    personBaseinfo = jsob.value("output").toObject().value("baseinfo").toObject();
    personInsuinfo = jsob.value("output").toObject().value("insuinfo")[0].toObject();
    personIdetinfo = jsob.value("output").toObject().value("idetinfo")[0].toObject();
    //1100结束

    //2203A,就诊信息上传
    statusMsg = "2203 就诊信息上传。。。";



    inpu = d.object();
    inpud = d.object();
    in = d.object();

    if(!putBaseIn( in, "2203A")) {
        return false;
    }

    inpu.insert("mdtrt_id", patientInfo["mdtrt_id"]);   //就诊ID
    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());   //人员编号
    //inpu.insert("med_type","110104");//	医疗类别 110104 门诊统筹， 11 普通门诊， 12 挂号
    inpu.insert("med_type","11");//	医疗类别 110104 门诊统筹， 11 普通门诊， 12 挂号
    inpu.insert("begntime", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));//	开始时间
    inpud.insert("mdtrtinfo",inpu);

    inpu = d.object();

    QJsonArray djsar;//诊断

    //QMap<QString, QString>::iterator iter = diag.begin();
    QMap<QString, QString> mp;
    int i = 0;
    foreach(mp, diag){
        i ++;
        qDebug()<<"mp"<<mp["deptName"]<<mp["diag_code"]<<mp["diag_name"];
        inpu.insert("diag_type", "1");   //诊断类别：1 西医主要诊断， 2 中医主病诊断	3 中医主证诊断
        inpu.insert("diag_srt_no", i );   //诊断排序号
        inpu.insert("diag_code", mp["diagCode"]); //诊断代码
        inpu.insert("diag_name", mp["diagName"]);//诊断名称
        qro->exec("select dept_name from com_department where dept_code='"+mp["deptCode"]+"'");
        qro->next();
        inpu.insert("diag_dept", qro->value(0).toString());   //诊断科室
        inpu.insert("dise_dor_no", mp["doctCode"]);   //诊断医生编码
        inpu.insert("dise_dor_name", mp["doctName"]);//诊断医生姓名
        inpu.insert("diag_time", mp["operDate"]);//诊断时间
        inpu.insert("vali_flag", "1");//有效标志
        djsar<<inpu;
    }

    inpud.insert("diseinfo", djsar);
    in.insert("input", inpud);
    indoc.setObject(in);
    qDebug()<< currentInfno + " indoc"<<indoc;

    indoc.setObject(in);

    //保存入参日志

    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    qDebug()<<" request " + currentInfno + " is started ";

    reply = manager.post(request,indoc.toJson());

    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。

    qDebug()<<" request " + currentInfno + " is returned ";

    statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意", currentInfno + " http 请求状态错误: " + statusCode.toString());
        return false ;
    }

    err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return false ;
    }

    btret = reply->readAll();
    t = QString::fromLocal8Bit(btret);

    jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意", currentInfno + " 返回信息解析错误 " + json_error.errorString());

        return false ;
    }
    qDebug()<< currentInfno + " outDoc "<<jsdc;
    jsob = jsdc.object();

    //保存出出参日志

    sq = "update com_business set v_out = '"
            + jsdc.toJson(QJsonDocument::Compact) + "' where jyls = '"
            + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }


    if(jsob.value("infcode").toInt() != 0){
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意", currentInfno + " 交易失败：" + t );
        return false ;
    }

    //2203结束
    statusMsg = "2205 撤销无效上传数据。。。";
    //2205,撤销费用明细上传
    //防止多次点击预结算上传重复数据，每次预结之前执行一次清理

    inpu = d.object();
    inpud = d.object();
    in = d.object();


    //putBaseIn(  in, "2205");
    if(!putBaseIn(  in, "2205")){

        return false;
    }

    inpu.insert("mdtrt_id", patientInfo["mdtrt_id"]);   //就诊ID
    inpu.insert("chrg_bchno", "0000");   //批咨与传“0000”，删除所有未结算数据
    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());//

    inpud.insert("data",inpu);
    in.insert("input", inpud);

    indoc.setObject(in);
    //保存入参日志
    qDebug()<< currentInfno + " indoc"<<indoc;


    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    reply = manager.post(request,indoc.toJson());

    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。

    qDebug()<<" request " + currentInfno + " is returned ";

    statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意", currentInfno + " http 请求状态错误: " + statusCode.toString());
        return false ;
    }

    err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return false ;
    }

    btret = reply->readAll();
    t = QString::fromLocal8Bit(btret);

    jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意", currentInfno + " 返回信息解析错误 " + json_error.errorString());

        return false ;
    }
    qDebug()<< currentInfno + " outDoc "<<jsdc;
    jsob = jsdc.object();

    //保存出出参日志

    sq = "update com_business set v_out = '"
            + jsdc.toJson(QJsonDocument::Compact) + "' where jyls = '"
            + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }
    /*
    //不对成功标志做判断
    if(jsob.value("infcode").toInt() != 0){
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意", currentInfno + " 交易失败：" + t );
        return ;
    }
*/
    //2205 结束
    statusMsg = "2204 上传费用明细。。。";
    //2204,费用明细上传

    in = d.object();
    inpu = d.object();
    inpud = d.object();
    //putBaseIn(  in, "2204");
    if(!putBaseIn(  in, "2204")){

        return false;
    }
    QJsonArray jsar;
    qro->exec("select seq_ftp_seq.nextval from dual");
    qro->next();
    chrg_bchno = qro->value(0).toString();

    for(int i = 0; i< mdXmmx.rowCount(); i++ ){//收费明细列表

        QString itm = mdXmmx.record(i).value("item_code").toString();

        bool compared = false;
        mp.clear();//检索品种是否属于医保目录
        foreach(mp, lstItemDetail){

            if(mp["item_code"] == itm){
                if(mp["has_compare"] == "1"){
                    compared = true;
                }
                break;
            }
        }
        if(!compared){
            nonInsuAmount += mdXmmx.record(i).value("own_cost").toDouble();
            continue;
        }
        inpu.insert("feedetl_sn", mdXmmx.record(i).value("mo_order").toString());//	费用明细流水号
        //inpu.insert("feedetl_sn", mp["MO_ORDER"]);
        inpu.insert("mdtrt_id", patientInfo["mdtrt_id"]);//	就诊ID
        inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());//	人员编号
        inpu.insert("chrg_bchno", chrg_bchno);//	收费批次号
        //inpu.insert("rxno", personBaseinfo.value("psn_no").toString());//	处方号
        inpu.insert("rx_circ_flag", "0");//	外购处方标志
        inpu.insert("fee_ocur_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));//	费用发生时间


        QMap<QString, QString> mmp;
        foreach(mmp, lstItemDetail){
            if( mmp["item_code"] == mdXmmx.record(i).value("item_code").toString()){
                //cost = mmp["center_code"];
                break;   //
            }
        }
        inpu.insert("med_list_codg", mmp["center_code"]);//	医疗目录编码-00110200001000003

        inpu.insert("medins_list_codg", mdXmmx.record(i).value("item_code").toString());//	医药机构目录编码
        inpu.insert("det_item_fee_sumamt", mdXmmx.record(i).value("own_cost").toDouble());//	明细项目费用总额

        inpu.insert("cnt", mdXmmx.record(i).value("rqty").toDouble());//	数量
        inpu.insert("pric", mdXmmx.record(i).value("unit_price").toDouble());//	单价

        inpu.insert("bilg_dept_codg", mdXmmx.record(i).value("doct_dept").toString());//	开单科室编码
        qro->exec("select dept_name from com_department where dept_code = '"
                  + mdXmmx.record(i).value("doct_dept").toString() + "'");
        qro->next();

        inpu.insert("bilg_dept_name", qro->value(0).toString());//	开单科室名称

        qro->exec("select si_code, empl_name from com_doctor_compare where empl_code = '"
                  + mdXmmx.record(i).value("doct_code").toString() + "'");
        qro->next();
        inpu.insert("bilg_dr_codg", qro->value(0).toString());//	开单医生编码
        inpu.insert("bilg_dr_name", qro->value(1).toString());//	开单医师姓名
        inpu.insert("hosp_appr_flag", "1");//	医院审批标志

        jsar.append(inpu);

    }

    if(jsar.size() == 0){
        QMessageBox::warning(NULL,"注意"," 项目列表不允许为空！ " );
        return false ;
    }

    inpud.insert("feedetail", jsar);
    in.insert("input", inpud);
    indoc.setObject(in);

    indoc.setObject(in);

    //保存入参日志
    qDebug()<< currentInfno + " indoc"<<indoc;
    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    reply = manager.post(request,indoc.toJson());

    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。

    qDebug()<<" request " + currentInfno + " is returned ";

    statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意", currentInfno + " http 请求状态错误: " + statusCode.toString());
        return false ;
    }

    err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return false ;
    }

    btret = reply->readAll();
    t = QString::fromLocal8Bit(btret);

    jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意", currentInfno + " 返回信息解析错误 " + json_error.errorString());

        return false ;
    }
    qDebug()<< currentInfno + " outDoc "<<jsdc;
    jsob = jsdc.object();

    //保存出出参日志

    sq = "update com_business set v_out = '"
            + jsdc.toJson(QJsonDocument::Compact) + "' where jyls = '"
            + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }


    if(jsob.value("infcode").toInt() != 0){
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意", currentInfno + " 交易失败：" + t );
        return false ;
    }

    ret2204 = jsob.value("output").toObject().value("result").toArray();

    //2204结束
    statusMsg = "2206 医保预结算。。。";
    //2206 预结算

    in = d.object();
    inpu = d.object();
    inpud = d.object();
    //putBaseIn(in, "2206A");
    if(!putBaseIn(  in, "2206A")){

        return false;
    }
    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());//人员编号

    //qro->exec("select mdtrt_cert_type from fin_ipr_siinmaininfo where mdtrt_id = '"+ patientInfo["mdtrt_id"] +"'");
    //qro->next();
    //mdtrt_cert_type = patientInfo["mdtrt_cert_type"];//qro->value(0).toString();

    inpu.insert("mdtrt_cert_type", mdtrt_cert_type);//	就诊凭证类型

    if(mdtrt_cert_type == "03"){
        if( "1" == pub::getStr(cardInfo,"|",1) ){   //0 社保卡， 1 老医保卡
            if(pub::getStr(cardInfo,"|",8).isEmpty()){
                inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",9));//老医保卡,8卡号9社保号
            }else{
                inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",8));//老医保卡,8卡号9社保号
            }
        }else{
            inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",4));   //社保卡,4卡号3社保号
        }
    }else if(mdtrt_cert_type == "02"){
        inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",2));

    }else if(mdtrt_cert_type == "01"){
        inpu.insert("mdtrt_cert_no", retScan.value("ecToken").toString());//	就诊凭证编号

    }

    //inpu.insert("med_type","110104");//	医疗类别 110104 门诊统筹， 11 普通门诊， 12 挂号
    inpu.insert("med_type","11");//	医疗类别 110104 门诊统筹， 11 普通门诊， 12 挂号
    inpu.insert("medfee_sumamt", QString::asprintf("%.2f",ui->leHjje->text().toDouble() - nonInsuAmount));//	医疗费总额
    inpu.insert("psn_setlway", "01");//	个人结算方式    01 按项目结算 02 按定额结算 09 其他 990104 按限额

    inpu.insert("mdtrt_id",  patientInfo["mdtrt_id"]);//	就诊ID
    inpu.insert("chrg_bchno", chrg_bchno);//	收费批次号
    inpu.insert("acct_used_flag","1" );//个人账户使用标志
    inpu.insert("insutype", personInsuinfo.value("insutype").toString());//险种类型

    QJsonObject ot;
    ot.insert("deve_flag","OwnSoft");
    ot.insert("dise_reim_mon","");

    inpu.insert("exp_content", ot);//	字段扩展
    inpud.insert("data",inpu);
    in.insert("input", inpud);

    indoc.setObject(in);

    //保存入参日志
    qDebug()<< currentInfno + " indoc"<<indoc;
    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    reply = manager.post(request,indoc.toJson());

    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。

    qDebug()<<" request " + currentInfno + " is returned ";

    statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意", currentInfno + " http 请求状态错误: " + statusCode.toString());
        return false ;
    }

    err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return false ;
    }

    btret = reply->readAll();
    t = QString::fromLocal8Bit(btret);

    jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意", currentInfno + " 返回信息解析错误 " + json_error.errorString());

        return false ;
    }
    qDebug()<< currentInfno + " outDoc "<<jsdc;
    jsob = jsdc.object();

    //保存出出参日志

    sq = "update com_business set v_out = '"
            + jsdc.toJson(QJsonDocument::Compact) + "' where jyls = '"
            + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }


    if(jsob.value("infcode").toInt() != 0){
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意", currentInfno + " 交易失败：" + t );
        return false ;
    }

    ret2206setlinfo = jsob.value("output").toObject().value("setlinfo").toObject();
    ret2206setldetail = jsob.value("output").toObject().value("setldetail").toObject();

    //医保预结算操作成功之后收费模式改为医保
    patientInfo["yb"] = "1";

    patientInfo["PAYKIND_CODE"] = "02";
    patientInfo["PACT_CODE"] = "2";
    patientInfo["PACT_NAME"] = "沈阳市保";




    //QString::asprintf("%.2f",);
    ybRet["Tot_Cost"] = QString::asprintf("%.2f", ret2206setlinfo.value("medfee_sumamt").toDouble()); //
    ybRet["Pay_Cost"] = QString::asprintf("%.2f", ret2206setlinfo.value("acct_pay").toDouble()); //账户支付
    //ybRet["Item_Ylcost"] = ret2206setlinfo.value("").toString();
    ybRet["Pub_Cost"] = QString::asprintf("%.2f", ret2206setlinfo.value("hifp_pay").toDouble());
    ybRet["Own_Cost"] = QString::asprintf("%.2f", ret2206setlinfo.value("psn_cash_pay").toDouble()); //现金支付

    ui->leZhzf->setText(ybRet["Pay_Cost"]);
    ui->leTczf->setText(ybRet["Pub_Cost"]);

    //医保计算总金额与项目列表总金额一致，列表项目全部为医保品种
    if(ybRet["Tot_Cost"] == ui->leHjje->text()){
        ui->leYjxj->setText(ybRet["Own_Cost"]); //医保结算之后需要支付的现金
    }else{   //项目列表中有非医保品种
        //实际需要缴费金额 = 医保品种需要支付的现金 + 非医保品种金额
        double yjje = ybRet["Own_Cost"].toDouble() +
                (ui->leHjje->text().toDouble() - ybRet["Tot_Cost"].toDouble());
        ui->leYjxj->setText(QString::asprintf("%.2f",yjje));
    }

    ui->leSf->setText(ui->leYjxj->text());  //

    if(ui->leYjxj->text() == "0.00"){
        ui->leYjxj->setPalette(palCashNormal);
    }else{
        ui->leYjxj->setPalette(palCashUnderline);
    }

    return true;
}

void Form_sk::on_pbPrint_clicked()   //发票打印
{
    QMap<QString, QString> mp;
    foreach(mp , lstInvoiceInfo){
        mpPage.clear(); //清空页面数据
        mpPage["发票号"] = mp["invoice_no"];
        mpPage["姓名"] = patientInfo["PATIENT_NAME"];
        mpPage["性别"] = patientInfo["SEX_CODE"] == "M" ? "男" : "女";
        mpPage["收费类别"] = patientInfo["PACT_NAME"];
        mpPage["医保卡号"] = patientInfo["MCARD_NO"];
        mpPage["门诊号"] = patientInfo["CARD_NO"];
        mpPage["身份证号"] = patientInfo["IDENNO"];
        mpPage["处方医师"] = getDoctCode(mp["invoice_no"]);
        mpPage["执行科室"] = mp["dept_name"];
        QStringList fees = getFeeTypes(mp["invoice_no"]);
        int idx = 1;
        foreach(QString s, fees){
            mpPage["费别"+QString::number(idx)] = s;
            idx++;
        }
        mpPage["项目名头"] = "项目             规格        数量     单价";
        if(mp["printItem"] != "np"){  //明细项目是否打印
            idx = 1;
            QStringList items = getItems(mp["invoice_no"]);
            foreach(QString s, items){
                mpPage["项目"+QString::number(idx)] = pub::getStr(s, "^", 1);
                mpPage["规格"+QString::number(idx)] = pub::getStr(s, "^", 2);
                mpPage["数量"+QString::number(idx)] = pub::getStr(s, "^", 3);
                mpPage["单价"+QString::number(idx)] = pub::getStr(s, "^", 4);
                idx++;
                if(idx > 10){ //每张发票显示项目明细最多10项
                    break;
                }
            }
        }

        mpPage["合计"] = mp["tot_cost"];
        mpPage["大写"] = pub::bigW(mp["tot_cost"].toDouble());
        mpPage["医院名称"] = pub::hos_name;
        mpPage["操作员"] = pub::usr_code;
        QDateTime dt = QDateTime::currentDateTime();
        QString d = dt.toString("yyyy");
        d.append("    ");
        d.append(dt.toString("MM"));
        d.append("    ");
        d.append(dt.toString("dd"));
        d.append("    ");
        d.append(dt.toString("hh:mm:ss"));

        mpPage["日期"] = d;
        if(patientInfo["yb"] == "1"){//医保支付，显示支付之后的卡余额
            mpPage["卡余额"] = mp["ybzhye"];
        }
        //mpPage["统筹"] = mp["pub"];
        mpPage["账户"] = mp["pay_cost"];
        double yf = mp["own_cost"].toDouble();  //应付现金
        double sf =  mp["real_cost"].toDouble();    //实付现金
        if(qFuzzyCompare(yf, sf)){  //无四舍五入
            mpPage["个人"] =mp["own_cost"];
        }else{
            mpPage["个人"] =mp["real_cost"] + " (" + mp["own_cost"] + ")";
        }

        printPage();
    }
}

void Form_sk::printPage()
{
    pnt->begin(prt);
    QString item, mode,print_item,font;
    QFont ft=QFont();
    double top,left,width,height,size;
    int position;
    qrm->prepare("select p_type,p_item,p_top,p_left,p_width,p_height,"
                 "p_font_name,p_font_size,p_position,p_mode,p_print_item,"
                 "p_item_type from com_printer_setting where p_type = '门诊收据'");
    if(!qrm->exec()){
        QMessageBox::information(this,"错误","读取处方格式数据表失败：" + qrm->lastError().text());
        return;
    }
    while(qrm->next()){
        if(qrm->value("p_item_type").toString() == "item"){

            item = qrm->value(1).toString();
            top = qrm->value(2).toDouble();
            left = qrm->value(3).toDouble();
            width = qrm->value(4).toDouble();
            height = qrm->value(5).toDouble();
            font = qrm->value(6).toString();
            size = qrm->value(7).toDouble();
            position = qrm->value(8).toInt();
            mode = qrm->value(9).toString();
            print_item = qrm->value(10).toString();
            item = mpPage.value(item);
            if(item.isEmpty()){
                continue;   //空值不打印
            }
            QString outText;    //输入文本
            if(mode == "1"){
                outText = print_item + "：" + item;
            }else if(mode == "0"){
                outText =  item;
            }else  if(mode == "3"){
                outText =  print_item ;
            }

            //QFontMetrics fm(font, prt);
            ft.setPixelSize(int(ptScale * size));
            ft.setFamily(font);
            QFontMetrics fm(ft, prt);
            int pixelsWide = fm.width(outText);
            if(pixelsWide > width * ptScale){//超过预定格式，缩小字号
                size = size * ( width * ptScale / pixelsWide );//
                ft.setPixelSize(int(ptScale * size));
                ft.setFamily(font);
            }

            pnt->setFont(ft);
            const QRect rect = QRect( left * ptScale, top * ptScale, width * ptScale, height * ptScale);
            QRect boundingRect;
            pnt->drawText(rect, position, outText, &boundingRect);
        }
    }
    pnt->end();
}

bool Form_sk::saveSI(QString invo_no)
{
    //invo_no发票号
    QString balanceNo = QString::number(patientInfo["maxBalanceNo"].toInt() + 1);
    patientInfo["maxBalanceNo"] = balanceNo;
    patientInfo["currentInvoNo"] = invo_no;     // patientInfo["currentInvoNo"]不为空，执行实际医保结算
    qDebug()<<"si"<<patientInfo["currentInvoNo"]<<"balanceNo"<<balanceNo;
    tmString = "医保数据结算，当前发票号：" + invo_no;
    ui->lbMode->setText(tmString);
    qApp->processEvents();  //刷新显示

    if(!ybjs(invo_no)){
        return false;
    }

    qro->prepare("insert into fin_ipr_siinmaininfo ("
                 " non_insu_amount,insutype, clr_type, clr_way, hifp_pay, med_type, medfee_sumamt, preselfpay_amt, "
                 " inscp_scp_amt, psn_cash_pay, fund_pay_sumamt, acct_pay, psn_type,"
                 "insuplc_admdvs,psn_no,mdtrt_id,ipt_otp_no,msgid,setl_id,mdtrt_cert_type,"
                 "trans_type,Inpatient_No,Balance_No,Invoice_No,Medical_Type,Patient_No,"
                 "Card_No,Mcard_No,App_No,Procreate_Pcno,Si_Begindate,Si_State,Name,"
                 "Sex_Code,Idenno,Spell_Code,Birthday,Empl_Type,Work_Name,Clinic_Diagnose,"
                 "Dept_Code,Dept_Name,Paykind_Code,Pact_Code,Pact_Name,Bed_No,In_Date,"
                 "In_Diagnosedate,In_Diagnose,In_Diagnosename,Oper_Code,Oper_Date,"
                 "Reg_No,Fee_Times,Hos_Cost,Year_Cost,Out_Date,Out_Diagnose,"
                 "Out_Diagnosename,Balance_Date,Tot_Cost,Pay_Cost,Pub_Cost,Item_Paycost,"
                 "Base_Cost,Item_Ylcost,Item_Paycost2,Own_Cost,Over_Cost,Valid_Flag,"
                 "Balance_State,Remark,Official_Cost,Type_Code,Person_Type,"
                 "Primarydiagnosecode,Operatecode1,Operatecode2,Operatecode3,"
                 "Primarydiagnosename,overtake_owncost,BUSINESSSEQUENCE,"
                 "SERIOUSILLNESS_IN_COST,SERIOUSILLNESS_COST,SERIOUSILLNESS_TOTAL,individualbalance"
                 ") values( "
                 + ybRet["nonInsuAmount"] + ","
                 "'" + ret2207setlinfo.value("insutype").toString() + "',"
                 "'" + ret2207setlinfo.value("clr_type").toString() + "',"
                 "'" + ret2207setlinfo.value("clr_way").toString() + "',"
                 "'" + QString::asprintf("%.2f",ret2207setlinfo.value("hifp_pay").toDouble()) + "',"
                 "'" + ret2207setlinfo.value("med_type").toString() + "',"
                 "'" + QString::asprintf("%.2f",ret2207setlinfo.value("medfee_sumamt").toDouble()) + "',"
                 "'" + QString::asprintf("%.2f",ret2207setlinfo.value("preselfpay_amt").toDouble()) + "',"
                 "'" + QString::asprintf("%.2f",ret2207setlinfo.value("inscp_scp_amt").toDouble()) + "',"
                 "'" + QString::asprintf("%.2f",ret2207setlinfo.value("psn_cash_pay").toDouble()) + "',"
                 "'" + QString::asprintf("%.2f",ret2207setlinfo.value("fund_pay_sumamt").toDouble()) + "',"
                 "'" + QString::asprintf("%.2f",ret2207setlinfo.value("acct_pay").toDouble()) + "',"
                 "'" + ret2207setlinfo.value("psn_type").toString() + "',"

                 "'" + personInsuinfo.value("insuplc_admdvs").toString()
                 + "','" + personBaseinfo.value("psn_no").toString()

                 + "','" + patientInfo["mdtrt_id"]
                 + "','" + patientInfo["ipt_otp_no"]
                 + "','" + msgid2207
                 + "','" + ret2207setlinfo.value("setl_id").toString()
                 + "','" + mdtrt_cert_type
                 + "','1',:Inpatient_No,:Balance_No,:Invoice_No,'11','',"
                   ":Card_No,:Mcard_No,'0','',To_Date('0001/1/1', 'YYYY-MM-DD'),'',"
                   ":Name,:Sex_Code,:Idenno,'',:Birthday,'','','',"
                   ":Dept_Code,:Dept_Name,:Paykind_Code,:Pact_Code,:Pact_Name,'',sysdate,"
                   "sysdate,'','',:Oper_Code,sysdate,:Reg_No,0,0,"
                   ":Year_Cost,sysdate,:Out_Diagnose,:Out_Diagnosename,"
                   "To_Date('0001/1/1', 'yyyy-mm-dd'),:Tot_Cost,:Pay_Cost,"
                   ":Pub_Cost,:Item_Paycost,:Base_Cost,:Item_Ylcost,:Item_Paycost2,"
                   ":Own_Cost, 0, '1', '1',:Remark,'0','1',:Person_Type,'','','','','',"
                   "'0','',0,0,0,:individualbalance)"
            );


    //qro->bindValue(":trans_type",mpPerson["trans_type"]);//交易类型，1正2负
    qro->bindValue(":Inpatient_No",patientInfo["CLINIC_CODE"]);//住院流水号,clinic_code
    qro->bindValue(":Balance_No", balanceNo);//结算序号
    qro->bindValue(":Invoice_No", invo_no);//发票号
    qro->bindValue(":Card_No", patientInfo["CARD_NO"]);//就诊卡号
    qro->bindValue(":Mcard_No", patientInfo["MCARD_NO"]);//医疗证号
    qro->bindValue(":Name", patientInfo["PATIENT_NAME"]);//姓名
    qro->bindValue(":Sex_Code",  patientInfo["SEX_CODE"]); //性别
    qro->bindValue(":Idenno", patientInfo["IDENNO"]);//身份证号

    QDateTime dt = QDateTime::fromString(patientInfo["BIRTHDAY"],"yyyy-MM-dd") ;
    qro->bindValue(":Birthday", dt);

    //qro->bindValue(":Birthday", QDate::fromString(patientInfo["BIRTHDAY"],"yyyyMMdd"));//生日
    qro->bindValue(":Dept_Code", patientInfo["Dept_Code"]);//科室代码
    qro->bindValue(":Dept_Name", patientInfo["Dept_Name"]); //科室名称
    qro->bindValue(":Paykind_Code", patientInfo["PAYKIND_CODE"]);//结算类别 1-自费  2-保险
    qro->bindValue(":Pact_Code", patientInfo["PACT_CODE"]); //合同代码
    qro->bindValue(":Pact_Name", patientInfo["PACT_NAME"]);//合同单位名称
    qro->bindValue(":Oper_Code", pub::usr_code);//操作员
    qro->bindValue(":Reg_No", patientInfo["regNo"]);//社保卡号
    qro->bindValue(":Year_Cost",0);
    qro->bindValue(":Out_Diagnose", patientInfo["Out_Diagnose"]);
    qro->bindValue(":Out_Diagnosename", patientInfo["Out_Diagnosename"]);
    qro->bindValue(":Tot_Cost", ybRet["Tot_Cost"]);//合计金额
    qro->bindValue(":Pay_Cost", ybRet["Pay_Cost"]); //账户支付
    qro->bindValue(":Pub_Cost", ybRet["Pub_Cost"]); //统筹支付
    qro->bindValue(":Own_Cost", ybRet["Own_Cost"]); //个人支付
    qro->bindValue(":Item_Ylcost", ybRet["Item_Ylcost"]);//乙类
    qro->bindValue(":Remark", patientInfo["remark"] );//险种类别2100返回
    qro->bindValue(":Person_Type", patientInfo["personType"]);//医疗待遇类别2100返回
    qro->bindValue(":individualbalance", ybRet["afterPay"]);

    if(!qro->exec()){
        QMessageBox::information(this,"错误","插入 fin_ipr_siinmaininfo 失败！"+qro->lastError().text());
        qDebug()<<qro->lastError().text();
        return false;
    }
    return true;
}

void Form_sk::uiInit()
{
    ui->pbYbjs->setEnabled(false);  //医保结算按钮
    ui->pbSfbc->setEnabled(false);  //收费确认按钮
    ui->pbPrint->setEnabled(false); //打印
    mdXmmx.setQuery(NULL);          //项目明细列表清空
    ui->leHjje->setText("");        //合计金额
    ui->leYjxj->setText("");        //应收金额
    ui->leZhzf->setText("");        //账户支付
    ui->rbX->setChecked(true);      //现金
    //ui->rbX->setEnabled(false);      //现金
    //ui->rbZ->setEnabled(false);     //身份证
    //ui->rbK->setEnabled(false);      //
    //ui->rbM->setEnabled(false);      //

}

bool Form_sk::ybjs(QString ivno)
{
    //真正执行收费操作时需要按每张发票计算医保结算结果

    nonInsuAmount = 0;
    if( ivno.isEmpty() ){    //发票号空
        return false;
    }

    //2204,费用明细上传
    //预结算不分发票只算总数，医保结算时需要按每张发票计算，所以要清除数据重新上传。

    QJsonObject in, inpu, inpud;
    QJsonDocument indoc, d;

    //putBaseIn(  in, "2204");
    if(!putBaseIn(  in, "2204")) return false;
    QJsonArray jsar;
    qro->exec("select seq_ftp_seq.nextval from dual");
    qro->next();
    chrg_bchno = qro->value(0).toString();

    QMap<QString, QString> mp;

    foreach(mp, lstItemDetail){

        //非本发票号关联的项目，不计算
        if( mp["invoice_no"] != ivno){
            qDebug()<<"非本发票品种"<<patientInfo["currentInvoNo"]<<mp["TRADE_NAME"];
            continue;   //不进行本轮计算
        }

        if( mp["has_compare"] == "0"){
            qDebug()<<"非医保品种"<<mp["TRADE_NAME"];
            nonInsuAmount += mp["RETAIL_PRICE"].toDouble() * mp["APPLY_NUM"].toDouble() / mp["PACK_QTY"].toDouble();
            continue;   //非医保品种，不进行医保计算
        }

        inpu.insert("feedetl_sn", mp["MO_ORDER"]);//	费用明细流水号
        inpu.insert("mdtrt_id", patientInfo["mdtrt_id"]);//	就诊ID
        inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());//	人员编号
        inpu.insert("chrg_bchno", chrg_bchno);//	收费批次号
        //inpu.insert("rxno", personBaseinfo.value("psn_no").toString());//	处方号
        inpu.insert("rx_circ_flag", "0");//	外购处方标志
        inpu.insert("fee_ocur_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));//	费用发生时间
/*
        sq = "select a.med_chrgitm_type, hilist_code, hilist_name "
             " from new_down_1312 a where a.hilist_code = '"
                + mp["center_code"]
                + "'";
        //+ "' and begndate < curdate() and (a.enddate is null or enddate > curdate())";

        if(!qrm->exec(sq)){
            QMessageBox::information(this,"错误", "查询 new_down_1312 失败！"+qrm->lastError().text());
            qDebug()<<qrm->lastQuery();
            return false;
        }
        if(!qrm->next()){
            QMessageBox::information(this,"错误", "new_down_1312 中找不到对应记录！");
            qDebug()<<qrm->lastQuery();
            return false;
        }
*/
        //inpu.insert("med_list_codg", mp["center_code"]);

        inpu.insert("med_list_codg", mp["center_code"]);//	医疗目录编码-00110200001000003

        inpu.insert("medins_list_codg", mp["item_code"]);//	医药机构目录编码
        inpu.insert("det_item_fee_sumamt", mp["own_cost"]);//	明细项目费用总额

        inpu.insert("cnt", QString::number( mp["APPLY_NUM"].toInt() ) );//	数量
        inpu.insert("pric", mp["RETAIL_PRICE"].toDouble() / mp["PACK_QTY"].toDouble() );//	单价
        inpu.insert("bilg_dept_codg", mp["doct_dept"]);//	开单科室编码
        qro->exec("select dept_name from com_department where dept_code = '"
                  + mp["doct_dept"] + "'");
        qro->next();

        inpu.insert("bilg_dept_name", qro->value(0).toString());//	开单科室名称

        //qro->exec("select si_code, empl_name from com_doctor_compare where empl_code = '" + mp["item_code"] + "'");
        //qro->next();
        inpu.insert("bilg_dr_codg", mp["doct_si_code"]);//	开单医生编码
        inpu.insert("bilg_dr_name", mp["doct_name"]);//	开单医师姓名
        inpu.insert("hosp_appr_flag", "1");//	医院审批标志

        jsar.append(inpu);

    }

    if(jsar.size() == 0){
        QMessageBox::warning(NULL,"注意"," 明细项目列表不允许为空！ " );
        return false ;
    }

    inpud.insert("feedetail", jsar);
    in.insert("input", inpud);
    indoc.setObject(in);
    qDebug()<< currentInfno + " indoc"<<indoc;

    indoc.setObject(in);

    //保存入参日志
    qDebug()<< currentInfno + " indoc"<<indoc;
    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    QNetworkReply* reply = manager.post(request,indoc.toJson());
    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。

    qDebug()<<" request " + currentInfno + " is returned ";

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意", currentInfno + " http 请求状态错误: " + statusCode.toString());
        return false;
    }

    QNetworkReply::NetworkError err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return false;
    }

    QByteArray btret = reply->readAll();
    QString t = QString::fromLocal8Bit(btret);

    QJsonParseError json_error;
    QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意", currentInfno + " 返回信息解析错误 " + json_error.errorString());

        return false;
    }
    qDebug()<< currentInfno + " outDoc "<<jsdc;
    QJsonObject jsob = jsdc.object();

    //保存出出参日志

    sq = "update com_business set v_out = '"
            + jsdc.toJson(QJsonDocument::Compact) + "' where jyls = '"
            + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }


    if(jsob.value("infcode").toInt() != 0){
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意", currentInfno + " 交易失败：" + t );
        return false;
    }

    ret2204 = jsob.value("output").toObject().value("result").toArray();

    //2204结束

    //2207A 开始

    in = d.object();
    inpu = d.object();
    inpud = d.object();

    //putBaseIn(in, "2207A");
    if(!putBaseIn(  in, "2207A")) return false;


    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());//人员编号
    inpu.insert("mdtrt_cert_type", mdtrt_cert_type);//	就诊凭证类型

    if(mdtrt_cert_type == "03"){
        if( "1" == pub::getStr(cardInfo,"|",1) ){   //0 社保卡， 1 老医保卡
            if(pub::getStr(cardInfo,"|",8).isEmpty()){
                inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",9) + "|" + busiCardInfo);//老医保卡,8卡号9社保号
            }else{
                inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",8) + "|" + busiCardInfo);//老医保卡,8卡号9社保号
            }
        }else{
            inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",4) + "|" + busiCardInfo);   //社保卡,4卡号3社保号
        }
    }else if(mdtrt_cert_type == "02"){
        inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",2) + "|" + busiCardInfo);

    }else if(mdtrt_cert_type == "01"){
        inpu.insert("mdtrt_cert_no", retScan.value("ecToken").toString());//	就诊凭证编号
    }

    //inpu.insert("med_type","110104");//	医疗类别 110104 门诊统筹， 11 普通门诊， 12 挂号
    inpu.insert("med_type", "11");//医疗类别    12,挂号


    double cost = 0;
    QMap<QString, QString> mmp;
    foreach(mmp, lstInvoiceInfo){
        if( mmp["invoice_no"] == ivno){
            cost = mmp["ocst"].toDouble();
            break;   //
        }
    }
    if(qFuzzyCompare(cost, 0)){
        QMessageBox::warning(NULL,"注意", currentInfno + " 失败，查不到发票金额。" );
        return false;
    }
    inpu.insert("medfee_sumamt", QString::asprintf("%.2f", cost - nonInsuAmount));//	医疗费总额
    inpu.insert("psn_setlway", "01");//	个人结算方式
    inpu.insert("mdtrt_id",  patientInfo["mdtrt_id"]);//	就诊ID
    inpu.insert("chrg_bchno", chrg_bchno);//	收费批次号
    inpu.insert("acct_used_flag","1" );//个人账户使用标志
    inpu.insert("insutype", personInsuinfo.value("insutype").toString());//险种类型

    /*
invono	发票号	字符型	20
fulamt_ownpay_amt	全自费金额	数值型	16,2
overlmt_selfpay	超限价金额	数值型	16,2
preselfpay_amt	先行自付金额	数值型	16,2
inscp_scp_amt	符合政策范围金额	数值型	16,2

*/

    QJsonObject qt;
    qt.insert("deve_flag","OwnSoft");
    qt.insert("dise_reim_mon","");

    inpu.insert("exp_content", qt);//	字段扩展
    inpud.insert("data",inpu);
    in.insert("input", inpud);

    indoc.setObject(in);
    //保存入参日志
    qDebug()<< currentInfno + " indoc"<<indoc;
    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    reply = manager.post(request,indoc.toJson());
    //QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。

    qDebug()<<" request " + currentInfno + " is returned ";

    statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意", currentInfno + " http 请求状态错误: " + statusCode.toString());
        return false;
    }

    //QNetworkReply::NetworkError
    err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return false;
    }

    btret = reply->readAll();
    t = QString::fromLocal8Bit(btret);

    //QJsonParseError json_error;

    jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意", currentInfno + " 返回信息解析错误 " + json_error.errorString());

        return false;
    }
    qDebug()<< currentInfno + " outDoc "<<jsdc;
    jsob = jsdc.object();

    sq = "update com_business set v_out = '"
            + jsdc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }

    //inp.append(patientInfo["CLINIC_CODE"]+"|"); //就诊流水号
    //inp.append(patientInfo["currentInvoNo"] + "|");//发票号

    if(jsob.value("infcode").toInt() != 0){
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意", currentInfno + " 交易失败：" + t );
        return false;
    }

    ret2207setlinfo = jsob.value("output").toObject().value("setlinfo").toObject();
    ret2207setldetail = jsob.value("output").toObject().value("setldetail").toObject();

    ybRet.clear();

    ybRet["Tot_Cost"] = QString::asprintf("%.2f", ret2207setlinfo.value("medfee_sumamt").toDouble()); //
    ybRet["Pay_Cost"] = QString::asprintf("%.2f", ret2207setlinfo.value("acct_pay").toDouble()); //账户支付
    //ybRet["Item_Ylcost"] = ret2206setlinfo.value("").toString();
    ybRet["Pub_Cost"] = QString::asprintf("%.2f", ret2207setlinfo.value("hifp_pay").toDouble());
    ybRet["Own_Cost"] = QString::asprintf("%.2f", ret2207setlinfo.value("psn_cash_pay").toDouble()); //现金支付
    ybRet["balc"] = QString::asprintf("%.2f", ret2207setlinfo.value("balc").toDouble()); //现金支付
    ybRet["nonInsuAmount"] = QString::asprintf("%.2f",nonInsuAmount);
    patientInfo["ybZhye"] = ybRet["balc"];
    //ui->leZhzf->setText(ybRet["Pay_Cost"]);
    qDebug()<<"ybRet "<<ybRet;

    //写入当前医保结算发票的应缴现金
    for(int id = 0; id<lstInvoiceInfo.length(); id++){
        if(lstInvoiceInfo[id]["invoice_no"] == ivno){
            //处理处方中包含非医保品种的情况
            double ybhj = ybRet["Tot_Cost"].toDouble(); //医保合计
            double fphj = lstInvoiceInfo[id]["tot_cost"].toDouble();   //发票合计
            double yjje = ybRet["Own_Cost"].toDouble();    //应缴现金
            //本发票医保计算总金额与项目列表总金额一致，列表项目全部为医保品种
            if( !qFuzzyCompare(ybhj, fphj)){  //项目列表中有非医保品种
                //实际需要缴费金额 = 医保品种需要支付的现金 + 非医保品种金额
                yjje = yjje + fphj - ybhj;
            }

            lstInvoiceInfo[id]["real_cost"] = QString::asprintf("%.2f",yjje);
            lstInvoiceInfo[id]["pay_cost"] = ybRet["Pay_Cost"];
            lstInvoiceInfo[id]["pub_cost"] = ybRet["Pub_Cost"];
            lstInvoiceInfo[id]["own_cost"] = QString::asprintf("%.2f",yjje);
            lstInvoiceInfo[id]["ybzhye"] = ybRet["balc"];
            lstInvoiceInfo[id]["nonInsuAmount"] = QString::asprintf("%.2f",nonInsuAmount);
            //计算支付本张发票之后账户余额
            /*
            double tt = ybRet["Tot_Cost"].toDouble();   //合计
            double py = ybRet["Pay_Cost"].toDouble();   //账户支付
            double count = patientInfo["ybZhye"].toDouble();    //当前余额
            if(qFuzzyCompare(tt, py)){  //合计金额与账户支付相等
                count = count - py ;    //计算支付之后的余额
                patientInfo["ybZhye"] = QString::asprintf("%.2f", count);   //交易后余额
            }else{      //合计金额与账户支付不等，说明账户余额不足，直接归零
                patientInfo["ybZhye"] = "0.0";
            }
            //支付本张发票之后的账户余额
            lstInvoiceInfo[id]["ybzhye"] = patientInfo["ybZhye"];
            //支付之后保存中间结果，以简化保存 fin_ipr_siinmaininfo 时的计算
            //ybRet["afterPay"] = patientInfo["ybZhye"];
            */
            ybRet["afterPay"] = ybRet["balc"];
        }
    }
    return true;    //医保交易成功标志

}

void Form_sk::onTimeOut()
{
    if(ui->lbMode->text().isEmpty()){
        ui->lbMode->setText(tmString);
    }else{
        ui->lbMode->setText("");
    }
    qApp->processEvents();  //刷新显示
}

bool Form_sk::putBaseIn( QJsonObject &in, QString code)
{

    currentMsgid = pub::getYbStrJ(code, patientInfo["CLINIC_CODE"]);   //
    if(currentMsgid.isEmpty()){
        QThread::msleep(1000);
        currentMsgid = pub::getYbStrJ(code, patientInfo["CLINIC_CODE"]);   //
        if(currentMsgid.isEmpty()){
            QMessageBox::information(this,"note",  code + " 申请交易流水号失败！");
            return false; //未能成功申请交易流水号
        }
    }

    currentInfno = code;

    if(code == "2207A"){
        msgid2207 = currentMsgid;
    }
    in.insert("infno", code);
    in.insert( "msgid", currentMsgid);
    in.insert("mdtrtarea_admvs", pub::hos_insuplc);
    if(!personInsuinfo.value("insuplc_admdvs").toString().isEmpty()){
        in.insert("insuplc_admdvs",personInsuinfo.value("insuplc_admdvs").toString());
    }

    in.insert("insuplc_admdvs","210100");
    in.insert("recer_sys_code", "OwnSoft");
    in.insert("dev_no","");
    in.insert("dev_safe_info","");
    in.insert("cainfo", pub::hos_secretcode);
    in.insert("signtype","");
    in.insert("infver", "V1.0");
    in.insert("opter_type", "1");
    in.insert("opter", pub::usr_code);
    in.insert("opter_name", pub::usr_name);
    in.insert("inf_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
    in.insert("fixmedins_code", pub::hos_ybbh);
    in.insert("fixmedins_name", pub::hos_name);
    in.insert("sign_no", pub::sign_no);

    return true;
}

bool Form_sk::searchBaseData()
{
    //取最后一条记录
    qro->prepare("select balance_no, remark, person_type, reg_no, individualbalance, mdtrt_id, "
                 " mdtrt_cert_type, ipt_otp_no, insuplc_admdvs"
                 " from Fin_Ipr_Siinmaininfo where Inpatient_No = :Inpatient_No And Type_Code = '1' "
                 " order by balance_no desc"
                 );
    qro->bindValue(":Inpatient_No", patientInfo["CLINIC_CODE"]);
    if(!qro->exec()){
        QMessageBox::information(this,"错误", "查询 Fin_Ipr_Siinmaininfo 失败！"+qro->lastError().text());
        qDebug()<<qro->lastQuery();

        return false;
    }

    if(!qro->next()){
        QMessageBox::information(this,"错误","未使用医保挂号，不能使用医保结算！");
        return false;
    }

    patientInfo["maxBalanceNo"] = qro->value(0).toString();
    patientInfo["remark"] = qro->value(1).toString();   //参保状态
    patientInfo["personType"] = qro->value(2).toString();
    patientInfo["regNo"] = qro->value(3).toString();    //社保号
    patientInfo["mdtrt_id"] = qro->value(5).toString();    //就诊id
    mdtrt_cert_type = qro->value(6).toString();    //支付方式 01电子，02身份证，03社保卡
    patientInfo["ipt_otp_no"] = qro->value(7).toString();    //
    patientInfo["insuplc_admdvs"] = qro->value(8).toString();    //

    if(mdtrt_cert_type == "03"){    //医保模式

        ui->rbK->setChecked(true);
    }else if(mdtrt_cert_type == "01"){

        ui->rbM->setChecked(true);
    }else if(mdtrt_cert_type == "02"){

        ui->rbZ->setChecked(true);
    }else{

        QMessageBox::information(this,"错误","找不到有效的医保支付方式！");

        ui->rbX->setChecked(true);

        return false;
    }

    //查询诊断
    diag.clear();// 清空诊断列表

    sq = "select t.clinicdiag_code, t.clinicdiag_name, doct_code,doct_name,dept_code,oper_date"
         " from met_ord_recipedetail t "
         " where t.clinic_code = '" + patientInfo["CLINIC_CODE"] + "' order by t.oper_date desc";

    if(!qro->exec(sq)){
        QMessageBox::information(this,"error","从 met_ord_recipedetail 提取诊断信息错误!");
        qDebug()<<qro->lastQuery();

        return false ;
    }
    if(!qro->next()){
        QMessageBox::information(this,"错误","找不到有效的诊断，无法向医保中心上传！");

        return false;
    }

    //QString docCod,docName,depCod;
    QMap<QString,QString> mp;
    bool find;  //是否已经存在该诊断

    while(true){
        find  = false;

        foreach (mp, diag){
            if(mp["diagCode"] == qro->value(0).toString() ){
                find = true;
                break;
            }
        }
        if(!find){//未找到，插入新值
            mp["diagCode"] = qro->value(0).toString();
            mp["diagName"] = qro->value(1).toString();
            mp["doctCode"] = qro->value(2).toString();
            mp["doctName"] = qro->value(3).toString();
            mp["deptCode"] = qro->value(4).toString();
            mp["operDate"] = qro->value(5).toDateTime().toString("yyyy-MM-dd HH:mm:ss");

            diag << mp;
        }

        if(!qro->next()){
            break;
        }
        qDebug()<<" diag qro->value(0).toString()"<<qro->value(0).toString();
    }
    return true;
}

bool Form_sk::scanCode()
{

    QJsonObject in; //入参
    QJsonObject inpu,inpud; // 入参 input 段
    QJsonDocument indoc;

    inpu.insert("businessType", "01301");     //用码类型, 结算
    inpu.insert("officeId", pub::dp_code);
    inpu.insert("officeName", pub::dp_name);
    inpu.insert("operatorId", pub::usr_code);
    inpu.insert("operatorName", pub::usr_name);
    inpu.insert("orgId", pub::hos_ybbh);
    in.insert("data", inpu);
    in.insert("orgId", pub::hos_ybbh);
    in.insert("transType", "ec.query");
    indoc.setObject(in);

    QString inp = indoc.toJson();

    char p1[8192];
    int ret = pub::EcQuery( inp.toLocal8Bit().data() , p1 );

    qDebug()<<"扫码 "<<indoc;


    if(ret != 0){

        QMessageBox::information(this,"错误","医保扫码失败！ ");
        qDebug()<<"医保扫码失败";

        return false;
    }

    QString ret1 = QString::fromLocal8Bit(p1); //获取出参

    QJsonParseError json_error;
    QJsonDocument jsdc = QJsonDocument::fromJson(ret1.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意","scanCode 返回信息解析错误 " + json_error.errorString());

        return false;
    }
    qDebug()<< "scan code outDoc "<<jsdc;

    sq = "insert into com_business (ywbh,user,jysj,jyfs,v_in,v_out) values "
         "('codeScan','" + pub::usr_code + "',DATE_FORMAT(now(),'%Y-%m-%d %T'),'code','"
            + indoc.toJson(QJsonDocument::Compact) + "','" + jsdc.toJson(QJsonDocument::Compact) + "')";
    if(!qrm->exec(sq)){
        QMessageBox::information(this,"注意","保存医保动态库交易日志失败！ ");
        qDebug()<<sq;
    }

    QJsonObject jsob = jsdc.object();

    if( !qFuzzyCompare(jsob.value("code").toDouble() , 0)){
        QMessageBox::information(this,"注意","scanCode 动态库返回失败: " + jsob.value("message").toString());
        return false;
    }

    retScan = jsob.value("data").toObject();
    return true;

}

bool Form_sk::readCard()
{

    QJsonObject inpu; // 入参 input 段
    QJsonDocument indoc;

    int ret = -1;
    char p1[2048];
    char p2[8192];

    ret = pub::ReadCardBas(p1, p2);

    if(ret != 0){
        QMessageBox::information(this,"错误","医保读卡失败！ ");
        qDebug()<<"医保读卡失败";

        return false;

    }
    cardInfo = QString::fromLocal8Bit(p1); //获取出参
    busiCardInfo= QString::fromLocal8Bit(p2); //获取出参

    QString ret1 = cardInfo;
    QString ret2 = busiCardInfo;

    sq = "insert into com_business (ywbh,user,jysj,jyfs,v_in,v_out) values "
         "('cardRead','" + pub::usr_code + "',DATE_FORMAT(now(),'%Y-%m-%d %T'),'card','','"
            + ret1 + "^" + ret2 + "')";
    if(!qrm->exec(sq)){
        QMessageBox::information(this,"注意","保存医保动态库交易日志失败！ ");
        qDebug()<<sq;
    }

    return true;
}

bool Form_sk::readIdCard()
{

    QJsonObject inpu; // 入参 input 段
    QJsonDocument indoc;

    int ret = -1;
    char p1[10240];
    char p2[10240];

    ret = pub::ReadSFZ(p1, p2);

    if(ret != 0){
        QMessageBox::information(this,"错误","身份证读卡失败！ ");
        qDebug()<<"身份证读卡失败";

        return false;

    }
    cardInfo = QString::fromLocal8Bit(p1); //获取出参
    busiCardInfo= QString::fromLocal8Bit(p2); //获取出参

    QString ret1 = cardInfo;
    QString ret2 = busiCardInfo;

    sq = "insert into com_business (ywbh,user,jysj,jyfs,v_in,v_out) values "
         "('cardRead','" + pub::usr_code + "',DATE_FORMAT(now(),'%Y-%m-%d %T'),'card','','"
            + ret1 + "^" + ret2 + "')";
    if(!qrm->exec(sq)){
        QMessageBox::information(this,"注意","保存医保动态库交易日志失败！ ");
        qDebug()<<sq;
    }

    return true;
}
